开发者

Form keyPress help

开发者 https://www.devze.com 2023-02-21 23:50 出处:网络
first of all, I needed a way to know when the control key was down, and here\'s the link: Form keyDown not working?

first of all, I needed a way to know when the control key was down, and here's the link: Form keyDown not working?

Thanks to them I got it working. But I noticed that was not my ultimate objective! Instead of checking for the control key on keyDown, I want to check for it on keyPress. But apparently I can't use

    If e.Control Then

    End If

On the

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

End Sub

Method.

Any ideas? I also want to check for when the key is no longer pressed...


New problem:

 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()
     开发者_Go百科   End If
        Label1.Text = controlActivated
    End Sub

That is inside a timer. For some reason it is always "False" unless I click somewhere with the control key pressed...


By the time you get the KeyPress event, which you won't when the form has any controls, the Control key state is already applied to the pressed key. So you'll get, say, 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, etcetera, through Ctrl+Z = 26. This is very likely what you want to do, you could also use the Control.ModifierKeys property:

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

Beware that many keys don't generate a KeyPressed event, like Ctrl+F1. KeyDown is required to test them.


You should use Control.ModifierKeys in whatever operation that should be affected by whether or not the control key is down. This timer's Tick event handler works fine:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消