表格keyPress帮助

时间:2011-04-03 21:06:46

标签: vb.net winforms visual-studio

首先,我需要一种方法来了解控制键何时关闭,这是链接:Form keyDown not working?

感谢他们,我得到了它的工作。但我注意到这不是我的终极目标! 我没有在keyDown上检查控制键,而是想在keyPress上检查它。但显然我不能使用

    If e.Control Then

    End If

Private Sub Form1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

End Sub

方法

有什么想法吗?我还想检查按键何时不再按下...


新问题:

 Private Sub controlTick(ByVal sender As Object, ByVal e As EventArgs)
        If Control.ModifierKeys = Keys.Control Then
            controlActivated = True
            PictureBox2.Invalidate()
        End If
        If Control.ModifierKeys <> Keys.Control Then
            controlActivated = False
            PictureBox2.Invalidate()
        End If
        Label1.Text = controlActivated
    End Sub

那是在计时器内。由于某些原因它总是“假的”,除非我按下控制键的某个地方点击......

1 个答案:

答案 0 :(得分:1)

当您获得KeyPress事件时,当表单有任何控件时您不会这样做,Control键状态已经应用于按下的键。所以你会得到,比方说,Ctrl + V:

Private Sub Form1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
    If e.KeyChar = ChrW(22) Then
        MessageBox.Show("Ctrl+V pressed")
    End If
End Sub

Ctrl + A = 1,等等,通过Ctrl + Z = 26.这可能是非常您可能想要做的事情,您也可以使用Control.ModifierKeys属性:

    If Control.ModifierKeys = Keys.Control Then
        MessageBox.Show("Control key pressed")
    End If

请注意,许多键不会生成KeyPressed事件,例如Ctrl + F1。需要KeyDown来测试它们。


您应该在控制键是否关闭的任何操作中使用Control.ModifierKeys。这个计时器的Tick事件处理程序工作正常:

Private Sub timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
    Dim controlActivated As Boolean
    If (Control.ModifierKeys And Keys.Control) = Keys.Control Then
        controlActivated = True
    End If
    Label1.Text = controlActivated.ToString()
End Sub