c#如何实现锁定键盘快捷键

2025-01-02 14:00:17
推荐回答(1个)
回答1:

这个东西要调用用API的键盘钩子来写哦!
给你个例子:
IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)

{

if( code < 0 ) return CallNextHookEx(_nextHookPtr,code, wparam, lparam); //返回,让后面的程序处理该消息

return (IntPtr) 1; //直接返回了,该消息就处理结束

}

实现过程:

1、新建一个C#的WindowsApplication

2、在Form1中,添加下面一些变量:

internal enum HookType //枚举,钩子的类型

{

//MsgFilter = -1,

//JournalRecord = 0,

//JournalPlayback = 1,

Keyboard = 2,

//GetMessage = 3,

//CallWndProc = 4,

//CBT = 5,

//SysMsgFilter = 6,

//Mouse = 7,

//Hardware = 8,

//Debug = 9,

//Shell = 10,

//ForegroundIdle = 11,

//CallWndProcRet = 12,

//KeyboardLL = 13,

//MouseLL = 14,

};

IntPtr _nextHookPtr; //记录Hook编号

3、在Form1中引入必须的API

[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId(); //取得当前线程编号的API

[DllImport("User32.dll")]

internal extern static void UnhookWindowsHookEx(IntPtr handle); //取消Hook的API

[DllImport("User32.dll")]

internal extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hinstance, int threadID); //设置Hook的API

[DllImport("User32.dll")]

internal extern static IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam); //取得下一个Hook的API

4、声明一个实现的委托

internal delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam);

5、添加自己的Hook处理过程

IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)

{

if( code < 0 ) return CallNextHookEx(_nextHookPtr,code, wparam, lparam); //返回,让后面的程序处理该消息

if( wparam.ToInt32() == 98 || wparam.ToInt32() == 66 ) //如果用户输入的是 b

{

this.textBox1.Text = "a";

return (IntPtr) 1; //直接返回了,该消息就处理结束了

}

else

{

return IntPtr.Zero; //返回,让后面的程序处理该消息

}

}

6、添加加入Hook链和从Hook链中取消的函数

public void SetHook()

{

if( _nextHookPtr != IntPtr.Zero ) //已经勾过了

return;

HookProc myhookProc = new HookProc(MyHookProc); //声明一个自己的Hook实现函数的委托对象

_nextHookPtr = SetWindowsHookEx((int)HookType.Keyboard, myhookProc , IntPtr.Zero , GetCurrentThreadId()); //加到Hook链中

}

public void UnHook()

{

if( _nextHookPtr != IntPtr.Zero )

{

UnhookWindowsHookEx(_nextHookPtr); //从Hook链中取消

_nextHookPtr = IntPtr.Zero;

}

}

7、在Form1的Load事件中添加 SetHook() , 在Form1的closing 事件中添加 UnHook()

private void Form1_Load(object sender, System.EventArgs e)

{

SetHook();

}

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

{

UnHook();

}