我正在编写一种安全应用程序
它记录键盘键..
我想隐藏应用程序,然后在用户按下某个键时显示它
我尝试了以下方法
隐藏按钮 :
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);
}
但是无论我按多少次键..我都不会显示!
我该怎么办??
正如其他人所说,你的应用将没有输入焦点,也不会侦听按键。
您需要在user32.dll
中挂接到RegisterHotKey,例如:
[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();
}
您需要确保在应用关闭时取消注册密钥:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!globalHotKey.Unregister())
{
Application.Exit();
}
}
这是因为您的应用程序没有输入焦点,因此不会拾取按键。当应用程序没有焦点时,需要挂接到较低级别的操作系统以获取键盘输入。
此处发布并回答了类似的问题:C# 应用程序中的全局键盘捕获
阅读文档?Aan 应用程序仅获取其窗口的按键。从逻辑上讲,这意味着隐藏窗口无法按键。
您挂接到表单处理程序,因此您只能看到表单上的按压,这些按压是不可见的,因此永远无法获得按键的焦点。
您可以在Windows中使用HOOKS来挂钩到常规处理中,但会产生副作用(即其他程序也会做出反应或阻止键)。
我建议研究一下:
从 C# 处理全局鼠标和键盘挂钩
从某种意义上说,你想要的不在.net功能之外,必须通过Windows API实现,因此必须使用本地语言。但是,当您通过 winAPI 接收输入时,可以使用链接到的项目 i 作为指南将其传递给应用程序。