之前一直苦苦纠结怎么实现这个问题,今天无意间发现了 窗体上有 keypriview这个属性
后经过查找相关资料,了解它是用于窗体捕捉键盘上按下的键
只要新建一个窗体,将此属性设置为true,便可以轻松实现这个功能。
方法一:
使用提交为 me.keydown完成
Private Sub form_keypress(sender As Object,e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Escape Then
Dim messge As New MSG
messge.head.Text = "即将退出系统"
messge.msgP.Text = "按下enter退出系统,esc返回..."
messge.Show()
End If
If e.KeyCode = Keys.F4 Then
Dim messge As New MSG
messge.head.Text = "F4"
messge.msgP.Text = "你按下了F4"
messge.Show()
End If
If e.KeyCode = Keys.F5 Then
Dim messge As New MSG
messge.head.Text = "F5"
messge.msgP.Text = "你按下了F5"
messge.Show()
End If
End Sub
这样可以轻松捕捉键盘上的所有键
esc举例:
F4 举例
F5举例
这里再例举一种方法:handles me.keypress
Private Sub form_keypress(sender As Object,e As KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = ChrW(27) Then
Dim messge As New MSG
messge.head.Text = "即将退出系统"
messge.msgP.Text = "按下enter退出系统,esc返回..."
messge.Show()
End If
If e.KeyChar = Chr(115) Then
Dim messge As New MSG
messge.head.Text = "F4"
messge.msgP.Text = "你按下了F4"
messge.Show()
End If
If e.KeyChar = Chr(116) Then
Dim messge As New MSG
messge.head.Text = "F5"
messge.msgP.Text = "你按下了F5"
messge.Show()
End If
End Sub
但是,不幸的是这种方式不能捕捉到F1-F12,以及一些特殊的键,比如shift等
当然还可以用handles me.keyup也是可以实现的