使用鼠标滚轮和VB.NET中的Ctrl控制WinForms的缩放级别

AZh*_*Zhu 6 vb.net scroll zoom ctrl winforms

如果我有一个winform,我是否可以通过Ctrl +鼠标滚轮来了解如何在应用程序中显示字体的缩放级别(以及应用程序窗口本身)?我看到Scroll Wheel事件中有一个Delta,但不确定它是如何工作的.有没有我可以研究的代码示例?

非常感谢所有的帮助!

Ton*_*gan 6

我怀疑你可以测试:

(VB.NET):

If (ModifierKeys And Keys.Control) = Keys.Control Then
Run Code Online (Sandbox Code Playgroud)

(C#):

if( (ModifierKeys  & Keys.Control) == Keys.Control )
Run Code Online (Sandbox Code Playgroud)

检查控制键是否关闭.


Ale*_*fie 5

您必须处理KeyDownKeyUp事件以确定是否Ctrl按下了键.此值应存储在类级别,因为除了KeyDownKeyUp事件之外的其他子例程将使用它.

然后编写代码来处理表单的MouseWheel事件.向下滚动(朝向你)会导致该Delta属性的负值MouseEventArgs.向上滚动显然是相反的.Delta属性的值始终为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
Run Code Online (Sandbox Code Playgroud)

有关您的问题的更多信息,请阅读以下内容:

  1. MSDN:Control.KeyDown事件
  2. MSDN:Control.KeyUp事件
  3. MSDN:Control.MouseWheel事件
  4. MSDN:MouseEventArgs类