从.NET锁定Windows(如"Windows + L")的方法如下:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class KeyboardHook
{
private const int WM_HOTKEY = 0x312;
private const int MOD_ALT = 0x1;
private const int MOD_CONTROL = 0x2;
private const int MOD_SHIFT = 0x4;
private const int MOD_WIN = 0x8;
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private int key;
private IntPtr hWnd;
private int id;
public event EventHandler HotKeyPressed;
public KeyboardHook(int key, Keys modifiers, Form form)
{
this.key = key;
this.hWnd = form.Handle;
id = this.GetHashCode();
RegisterHotKey();
form.Disposed += (sender, args) => UnregisterHotKey();
}
private void RegisterHotKey()
{
if (!RegisterHotKey(hWnd, id, GetModifierFlag(), key))
{
throw new ApplicationException("Unable to register hot key.");
}
}
private void UnregisterHotKey()
{
UnregisterHotKey(hWnd, id);
}
private int GetModifierFlag()
{
return 0;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY && (int)m.WParam == id)
{
OnHotKeyPressed();
}
base.WndProc(ref m);
}
private void OnHotKeyPressed()
{
HotKeyPressed?.Invoke(this, EventArgs.Empty);
}
}
private KeyboardHook keyboardHook;
private void InitializeKeyboardHook()
{
keyboardHook = new KeyboardHook(Keys.L, Keys.None, this);
keyboardHook.HotKeyPressed += (sender, args) => LockWorkStation();
}
[DllImport("user32.dll")]
private static extern bool LockWorkStation();
InitializeKeyboardHook()
方法。public MainForm()
{
InitializeComponent();
InitializeKeyboardHook();
}
现在,当您按下"Windows + L"组合键时,系统将锁定屏幕。请注意,这个方法仅适用于Windows操作系统。
领取专属 10元无门槛券
手把手带您无忧上云