如何设置VB.NET 窗体的全局热键(快捷键),很多人都为这个头疼,看到网上有很多的例子,但是都感觉好复杂,越看越糊涂。经过笔者的研究,把代码做了最简化的处理,使您一看就明白。本文使用API函数注册热键表,下面代码可以直接复制运行,不用做任何修改,方便您测试学习。
关于半全局热键(只对一个窗体或控件集有效)的定义,我在另一篇博文中有说明(章鱼哥出品—VB.Net 自定义快捷键详解之半全局快捷键)
<p> </p><p>'******************************************************************************** </p>'作者:章鱼哥 QQ:3107073263 群:309816713 '需要源码或是有好的建议请联系我 '主要内容: ' 利用API函数设置全局热键(快捷键)的流程和实现 '实现功能: ' 按下Shift+Q时 触发Button1的Click事件 ' 按下Ctrl+D时,触发Button2的Click事件 '********************************************************************************* Public Class Form1 '声明注册热键API函数 Public Declare Function RegisterHotKey Lib "user32" (ByVal hWnd As Integer,ByVal id As Integer,ByVal fsModifiers As Integer,ByVal vk As Integer) As Integer '声明注销热键API函数 Public Declare Function UnregisterHotKey Lib "user32" (ByVal hWnd As Integer,ByVal id As Integer) As Integer Public Const WM_HOTKEY As Short = &H312S '热键消息ID,此值固定,不能修改 Public Const MOD_ALT As Short = &H1S 'ALT按键ID Public Const MOD_CONTROL As Short = &H2S 'Ctrl Public Const MOD_SHIFT As Short = &H4S 'Shift Public uVirtKey1,Modifiers,idHotKey As Integer Private Sub Form1_Load(ByVal sender As Object,ByVal e As System.EventArgs) Handles MyBase.Load idHotKey = 1 '注册的热键的消息ID,这个值可以随便定义,只要与下面两个参数对应即可 Modifiers = MOD_SHIFT '辅助键为Shift uVirtKey1 = Keys.Q '注册的热键为Shift+Q '注册热键 RegisterHotKey(Me.Handle.ToInt32,idHotKey,uVirtKey1) '注册的热键为Shift+Q RegisterHotKey(Me.Handle.ToInt32,2,MOD_CONTROL,Keys.D) '注册的热键为Ctrl+D。这里和上步一样,我把参数直接写了,没有先赋值,相信大家都明白 End Sub '窗体的消息处理函数 Protected Overrides Sub WndProc(ByRef m As Message) If m.Msg = WM_HOTKEY Then '判断是否为热键消息 Select Case m.WParam.ToInt32 '判断热键消息的注册ID Case 1 Button1_Click(Nothing,Nothing) 'Shift+Q Case 2 Button2_Click(Nothing,Nothing) 'Ctrl+D End Select End If MyBase.WndProc(m) '循环监听消息 End Sub '按钮1的Click事件 Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "此时触发按钮1,快捷键" & Button1.Text End Sub '按钮2的Click事件 Private Sub Button2_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button2.Click TextBox1.Text = "此时触发按钮2,快捷键" & Button2.Text End Sub '最后别忘记注销热键哦 Private Sub Form1_Closing(ByVal sender As Object,ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing UnregisterHotKey(Me.Handle.ToInt32,uVirtKey1) UnregisterHotKey(Me.Handle.ToInt32,Keys.D) End Sub End Class
问题:本来是想使用Application.AddMessageFilter 方法的,但是后来发现单个按键的快捷键还能实现,但是组合快捷键就不容易实现了,有大神实现的,请赐教
原文链接:https://www.f2er.com/vb/257771.html