设置VB.NET 窗体的全局热键


 不少人有给程序添加全局热键的需求。网上随便一搜, 就能找到不少介绍windows下如何实现的方式. 下面的代码以VB为例,教你如何书写全局热键代码!就是传说中的老板键!!!

   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, Modifiers, 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  

 

点击数: 1057    打印  添加到收藏   发布时间: 2016-12-03




上一篇:产生随机注册名称和信息的方法
下一篇:使用STM32提供的DSP库函数进行FFT变换





» 相关内容
  程序调用其他dll或com组件的参..
  mornsun隔离型DCDC输入输出共..
  .Net强制退出当前程序并彻底清..
  Matlab绘制表面平滑的3D图形-..
  激光致眩武器介绍
  CD4046锁相环的说明
  USB供电对音频设备可能的电流..
  碳化硅光源的电阻随温度变化研..
  引力波探测技术要点
  秋风起时
  谐波失真及评价方法
  USB枚举过程描述
  也说“筷搜”,靠谱吗?
  MAC睿频的效果,你懂得
  matlab的try-catch语句调试不..