WPF學習日誌 ~ CaptureMouse ~

CaptureMouse顧名思義是捕捉滑鼠,那捕捉滑鼠要做什麼呢?
當我們捕捉住滑鼠的訊號之後,當滑鼠離開了Winddow的範圍之外,我們仍然可以收到MouseMove以及MouseUp的事件,這可以利用在縮/放部分,如果你有用過Blend(或是跑過DirectX的sample)的話,在調整(縮/放)工作區大小時,是類似的感覺;下面測試捕捉滑鼠,利用移動的距離來改變TextBlock的字體大小,執行結果像是下圖這樣

下面我們來看看測試的程式碼
Class Window1
Dim sp As StackPanel
Dim tb As TextBlock
Dim p As New Point

Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
sp = New StackPanel
tb = New TextBlock
tb.Text = "Some String here"
tb.Background = Brushes.AliceBlue
tb.HorizontalAlignment = Windows.HorizontalAlignment.Center
tb.VerticalAlignment = Windows.VerticalAlignment.Center
sp.Children.Add(tb)
Me.Content = sp
End Sub

Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Input.MouseEventArgs)
MyBase.OnMouseMove(e)
If e.LeftButton = MouseButtonState.Pressed Then
Me.Title = e.GetPosition(sp).X & "," & e.GetPosition(sp).Y
If (e.GetPosition(sp).X - p.X) > 30 Then
tb.FontSize += 2
p = e.GetPosition(sp)
ElseIf (e.GetPosition(sp).X - p.X) < -30 Then
If tb.FontSize > 8 Then
tb.FontSize -= 2
End If
p = e.GetPosition(sp)
End If
End If
End Sub

Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Input.MouseButtonEventArgs)
MyBase.OnMouseDown(e)
p = e.GetPosition(sp)
Me.CaptureMouse()
End Sub

Protected Overrides Sub OnMouseUp(ByVal e As System.Windows.Input.MouseButtonEventArgs)
MyBase.OnMouseUp(e)
ReleaseMouseCapture()
End Sub
End Class

留言

這個網誌中的熱門文章

開啟cshtml檔案時,出現『並未將物件參考設定為物件執行個體』的錯誤訊息

無法設定中斷點 尚未載入符號檔

Windows 10年度更新後,IIS 網站出現 503 錯誤