gpt4 book ai didi

c# - 全局注册键盘按下

转载 作者:行者123 更新时间:2023-11-30 13:37:01 29 4
gpt4 key购买 nike

我正在编写一种安全应用程序

它记录键盘按键..

我想隐藏应用程序,然后在用户按下某个键时显示它

我尝试了以下

隐藏按钮:

    private void button4_Click(object sender, EventArgs e)
{
ShowInTaskbar = false;
this.Visible = false;
this.TopMost = true;
}

和关键事件

private void KeyEvent(object sender, KeyEventArgs e)
{

if (e.KeyCode == Keys.Control && e.Modifiers== Keys.F12) {
this.Visible = true;
}
}

当然还有表单加载

 private void Form2_Load(object sender, EventArgs e)
{
KeyPreview = true;
this.KeyUp+=new System.Windows.Forms.KeyEventHandler(KeyEvent);
}

但是无论我按下多少次按键..我都不会显示!!

我该怎么办??

最佳答案

正如其他人所说,您的应用不会有输入焦点,也不会监听按键。

您需要连接到 RegisterHotKeyuser32.dll 中,例如:

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

例子:

public class GlobalHotKey
{
private int modifier;
private int key;
private IntPtr hWnd;
private int id;

public GlobalHotKey(int modifier, Keys key, Form form)
{
this.modifier = modifier;
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}

public bool Register()
{
return RegisterHotKey(hWnd, id, modifier, key);
}

public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}

public override int GetHashCode()
{
return modifier ^ key ^ hWnd.ToInt32();
}

[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);
}

public static class Constants
{
public const int NOMOD = 0x0000;
public const int ALT = 0x0001;
public const int CTRL = 0x0002;
public const int SHIFT = 0x0004;
public const int WIN = 0x0008;
public const int WM_HOTKEY_MSG_ID = 0x0312;
}

用法:

private GlobalHotKey globalHotKey;

// Registering your hotkeys
private void Form2_Load(object sender, EventArgs e)
{
globalHotKey = new HotKeys.GlobalHotKey(Constants.CTRL, Keys.F12, this);
bool registered = globalHotKey.Register();

// Handle instances where the hotkey failed to register
if(!registered)
{
MessageBox.Show("Hotkey failed to register");
}
}

// Listen for messages matching your hotkeys
protected override void WndProc(ref Message m)
{
if (m.Msg == HotKeys.Constants.WM_HOTKEY_MSG_ID)
{
HandleHotkey();
}

base.WndProc(ref m);
}

// Do something when the hotkey is pressed
private void HandleHotkey()
{
if(this.Visible)
this.Hide();
else
this.Show();
}

您需要确保在应用关闭时取消注册 key :

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!globalHotKey.Unregister())
{
Application.Exit();
}
}

关于c# - 全局注册键盘按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26993172/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com