2011-03-01 91 views
5

如果我有一個winform,我可以知道如何控制應用程序中字體的縮放級別(以及顯然的應用程序窗口本身)通過使用Ctrl +鼠標滾輪?我發現滾輪事件中有一個Delta,但不知道這是如何工作的。有沒有我可以查看的代碼示例?在VB.NET中使用鼠標滾輪和Ctrl控制WinForms的縮放級別

非常感謝所有的幫助!

回答

4

您必須處理KeyDownKeyUp事件,以確定是否按住Ctrl鍵。此值應存儲在類級別,因爲除了KeyDownKeyUp事件之外,其他子例程都會使用此值。

然後您編寫代碼來處理表單的MouseWheel事件。向下滾動(朝向您)導致MouseEventArgsDelta屬性爲負值。向上滾動顯然是相反的。三角洲屬性的值始終是目前120

微軟的原因值如下:

目前,120的值是一個制動器的標準。如果引入更高分辨率的鼠標,WHEEL_DELTA的定義可能會變小。大多數應用程序應檢查積極或消極的價值,而不是總數。

在您的情況下,您只需檢查Delta的符號並執行操作。

這是實現基本的 '縮放' 功能的示例代碼:對

Public Class Form1 
    Enum ZoomDirection 
     None 
     Up 
     Down 
    End Enum 

    Dim CtrlIsDown As Boolean 
    Dim ZoomValue As Integer 

    Sub New() 

     ' This call is required by the designer. 
     InitializeComponent() 

     ' Add any initialization after the InitializeComponent() call. 
     ZoomValue = 100 
    End Sub 

    Private Sub Form1_KeyDown_KeyUp(ByVal sender As Object, _ 
            ByVal e As KeyEventArgs) _ 
       Handles Me.KeyDown, Me.KeyUp 

     CtrlIsDown = e.Control 
    End Sub 

    Private Sub Form1_MouseWheel(ByVal sender As Object, 
           ByVal e As MouseEventArgs) _ 
       Handles Me.MouseWheel 

     'check if control is being held down 
     If CtrlIsDown Then 
      'evaluate the delta's sign and call the appropriate zoom command 
      Select Case Math.Sign(e.Delta) 
       Case Is < 0 
        Zoom(ZoomDirection.Down) 
       Case Is > 0 
        Zoom(ZoomDirection.Up) 
       Case Else 
        Zoom(ZoomDirection.None) 
      End Select 
     End If 
    End Sub 

    Private Sub Zoom(ByVal direction As ZoomDirection) 
     'change the zoom value based on the direction passed 

     Select Case direction 
      Case ZoomDirection.Up 
       ZoomValue += 1 
      Case ZoomDirection.Down 
       ZoomValue -= 1 
      Case Else 
       'do nothing 
     End Select 

     Me.Text = ZoomValue.ToString() 
    End Sub 
End Class 

閱讀下列關於你的問題的更多信息:

  1. MSDN: Control.KeyDown Event
  2. MSDN: Control.KeyUp Event
  3. MSDN: Control.MouseWheel Event
  4. MSDN: MouseEventArgs Class
+0

非常感謝這樣詳細的答案!這就是我一直在尋找的一切! – AZhu 2011-03-02 14:46:33

+0

@ zhuanyi:我的快樂... – 2011-03-02 16:12:57

+0

只是一個問題,雖然...由於某種原因,我的代碼似乎能夠捕獲鼠標移動,但沒有按鍵和鍵部分,除非我使用鼠標點擊表單第一......是預期的還是我只是在做一些愚蠢的事情? – AZhu 2011-03-02 19:27:24

4

我懷疑,你可以測試:

(VB.NET):

If (ModifierKeys And Keys.Control) = Keys.Control Then 

(C#):

if((ModifierKeys & Keys.Control) == Keys.Control) 

檢查,如果控制鍵是下。

相關問題