C#实现全局热键响应,失去焦点情况下响应全局快捷键的方法

C#实现全局热键响应,失去焦点情况下响应全局快捷键

 

    1 、引入API注册和注销热键的函数,建立一个类文件,命名为 HotKey.cs ,代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;   //使用DllImport
using System.Windows.Forms;   //使用keys

    {

        class HotKey

        {

            [DllImport("user32.dll")]

            // 用于注册热键

            public static extern bool RegisterHotKey(

                IntPtr hWnd,                // 要定义热键的窗口的句柄

       

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C# 窗体中实现全局热键可以使用 Windows API 函数来实现。以下是一个示例代码: ```csharp using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; public partial class MainForm : Form { // 定义全局热键的 ID,可以为任意值,只要不重复即可 private const int HOTKEY_ID = 9000; // 定义 Windows API 函数 [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); // 定义热键的组合键和热键对应的键码 private const uint MOD_ALT = 0x0001; private const uint VK_F1 = 0x70; public MainForm() { InitializeComponent(); // 注册全局热键 RegisterHotKey(this.Handle, HOTKEY_ID, MOD_ALT, VK_F1); } protected override void WndProc(ref Message m) { base.WndProc(ref m); // 如果收到全局热键消息 if (m.Msg == 0x0312 && m.WParam.ToInt32() == HOTKEY_ID) { Debug.WriteLine("Hotkey pressed"); } } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); // 注销全局热键 UnregisterHotKey(this.Handle, HOTKEY_ID); } } ``` 在上面的示例中,我们定义了一个 `MainForm` 窗体,并在构造函数中注册了一个全局热键热键的组合键为 Alt + F1,热键的 ID 为 9000。当用户按下热键,我们会在控制台输出一条消息。 在窗体的 `WndProc` 方法中,我们判断收到的消息是否是全局热键消息,如果是,就执行相应的操作。在窗体关闭,我们需要注销全局热键,以释放资源。 需要注意的是,全局热键需要在 Windows 消息循环中进行注册和注销,因此必须在窗体中实现 `WndProc` 方法,并在其中处理相应的消息。同全局热键的组合键和热键对应的键码可以根据需求进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值