首页 > 编程语言 >c# 捕获系统快捷键并响应

c# 捕获系统快捷键并响应

时间:2024-10-11 12:00:41浏览次数:10  
标签:wParam IntPtr c# 捕获 private 快捷键 int Keys WM

private void GlobalKeyCapture_KeyDown(object sender, KeyEventArgs e)
{
    //判断当前进程是否是活动进程,以决定是否响应
    var currentProcess = getActiveProcess();
    if (currentProcess.Id != Process.GetCurrentProcess().Id)
        return;

    if (e.KeyCode == Keys.F)
    {
        var ctrl = Control.ModifierKeys.HasFlag(Keys.Control);
        if (ctrl)
            menuItemFind_Click(menuItemFind, new EventArgs());
    }
}

private void GlobalKeyCapture_KeyUp(object sender, KeyEventArgs e)
{
    //判断当前进程是否是活动进程,以决定是否响应
    var currentProcess = getActiveProcess();
    if (currentProcess.Id != Process.GetCurrentProcess().Id)
        return;

    if (e.KeyCode == Keys.F12)
    {
        
    }
    else if (e.KeyCode == Keys.F5)
    {
        
    }
    else if (e.KeyCode == Keys.Escape)
    {
        
    }
}

核心类:

public class GlobalKeyCapture : NativeWindow
{
    private const int WM_KEYDOWN = 0x0100;
    private const int WM_KEYUP = 0x0101;

    public event EventHandler<KeyEventArgs> KeyUp;
    public event EventHandler<KeyEventArgs> KeyDown;

    public GlobalKeyCapture()
    {
        CreateHandle(new CreateParams());
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_KEYUP)
        {
            Keys key = (Keys)m.WParam;
            OnKeyUp(new KeyEventArgs(key));
        }
        else if (m.Msg == WM_KEYDOWN)
        {
            Keys key = (Keys)m.WParam;
            OnKeyDown(new KeyEventArgs(key));
        }
        base.WndProc(ref m);
    }

    protected virtual void OnKeyUp(KeyEventArgs e)
    {
        KeyUp?.Invoke(this, e);
    }

    protected virtual void OnKeyDown(KeyEventArgs e)
    {
        KeyDown?.Invoke(this, e);
    }

    [DllImport("user32.dll")]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);


    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

    [DllImport("user32.dll")]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll")]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("kernel32.dll")]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

    private const int WH_KEYBOARD_LL = 13;
    private const int WM_SYSKEYDOWN = 0x0104;
    private const int WM_SYSKEYUP = 0x0105;

    private IntPtr hookId = IntPtr.Zero;
    private LowLevelKeyboardProc proc;

    public void StartCapturing()
    {
        proc = HookCallback;
        hookId = SetHook(proc);
    }

    public void StopCapturing()
    {
        UnhookWindowsHookEx(hookId);
    }

    private IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Keys key = (Keys)vkCode;

            if (wParam.ToInt32() == WM_KEYUP || wParam.ToInt32() == WM_SYSKEYUP)
            {
                OnKeyUp(new KeyEventArgs(key));
            }
            else if (wParam.ToInt32() == WM_KEYDOWN || wParam.ToInt32() == WM_SYSKEYDOWN)
            {
                OnKeyDown(new KeyEventArgs(key));
            }
        }
        return CallNextHookEx(hookId, nCode, wParam, lParam);
    }
}

 

标签:wParam,IntPtr,c#,捕获,private,快捷键,int,Keys,WM
From: https://www.cnblogs.com/nanfei/p/18458098

相关文章

  • SCI论文快速排版:word模板一键复制样式和格式【重制版】
    关注B站可以观看更多实战教学视频:hallo128的个人空间SCI论文快速排版:word模板一键复制样式和格式:视频操作视频重置版2SCI论文快速排版:word模板一键复制样式和格式【重制版】模板与普通文档的区别为了让读者更好地了解模板,下面简单介绍一下模板与普通文档的区别。模......
  • AMIS低代码平台,前端开发常见问题(样式篇css style)
    最近项目是基于amis低代码平台开发的,在开始开发的时候并未接受系统的学习,导致开发过程中遇到很多问题。由于,部分问题在文档中不能解决,且,当前搜索引擎找到关于amis的文档非常有限。故,整理在开发过程中遇到的问题以供参考。 本片主要说明的是关于样式(css,style)1.对于可以在......
  • Boc-Val-Ala-PAB-PNP|CAS号:1884578-00-0多肽化合物
    Boc-Val-Ala-PAB-PNP是一种多肽化合物,其中包含了多个保护基团和特定的氨基酸序列。下面是对该化合物的详细解析:基本信息英文名:Boc-Val-Ala-PAB-PNPCAS号:1884578-00-0分子式:C27H34N4O9分子量:558.58结构式:分子结构1.**Boc**(叔丁氧羰基):  -这是一种常用的氨基酸N端......
  • Boc-PEG4-Val-Ala-PAB-PNP|用于合成抗体偶联药物(ADC)
    Boc-PEG4-Val-Ala-PAB-PNP是一种化学物质,以下是对其的详细解析:一、基本信息英文名:Boc-PEG4-Val-Ala-PAB-PNP分子式:C27H34N4O9分子量:558.58存储条件:一般建议储存在2~8°C的环境中,保持干燥和密闭。结构式:二、化学结构Boc-PEG4-Val-Ala-PAB-PNP的化学结构主要由以下几个部分......
  • Fmoc-Val-Ala-OH|N-[芴甲氧羰基]-L-缬氨酰-L-丙氨酸|CAS号:150114-97-9
    Fmoc-Val-Ala-OH(也称为Fmoc-Val-Ala-O-t-butyl酯)是一种重要的化学物质,以下是对其的详细介绍:一、基本信息化学名称:N-[芴甲氧羰基]-L-缬氨酰-L-丙氨酸CAS号:150114-97-9分子式:C23H26N2O5分子量:410.47结构式:二、化学性质Fmoc-Val-Ala-OH是一种可降解的ADClinker,可用于合成抗......
  • The Network Program Log Two (Scapy)
    ​【Scapy】【使用scapy处理数据包】scapy的使用fromscapy.allimport*fromscapy.layers.inetimport*pac=dir(scapy.layers)print(pac) #执行代码后,会输出Scapy中的各层['builtins','cached','doc','file','loader','name&......
  • Automate PowerPoint to PDF Conversion in .NET
    AutomatePowerPointtoPDFConversionin.NETStreamlineworkflowsbyeliminatingtheneedformanualfileconversions,ensuringconsistentformattingandenhancingdocumentsecurity.Usinga.NETcomponenttoconvertPowerPointpresentations......
  • 雷赛运动控制卡库函数C#导出
    usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Runtime.InteropServices;namespaceHardware.ImportExternal//命名空间根据应用程序修改{publicdelegateuintDMC3K5K_OPERATE(IntPtroperate_data);///<summary>///......
  • abc374E Sensor Optimization Dilemma 2
    abc374E传感器优化困境2#include<bitsstdc++.h>#definelllonglong#defineN105usingnamespacestd;//最小值最大,二分?//猜测最小值,每一个过程都要大于最小值,如果可行,就放大intn;llans,X;structNode{ lla,b,p,q;}c[105];intchk(llw){//猜测的是产品个数(加......
  • 基于大型语言模型爬虫项目Crawl4AI介绍
        Crawl4AI是一款专为大型语言模型(LLMs)和AI应用设计的开源网页爬虫和数据提取工具。最近挺火的开源AI网络爬虫工具:Crawl4AI可以直接用于大语言模型和AI应用。性能超快,还能输出适合大语言模型的格式,比如JSON、清理过的HTML和markdown。它还支持同时爬取多个网址,能提取所有......