【发布时间】:2018-02-11 06:56:12
【问题描述】:
所以我有一个带有表单的 C# 控制台应用程序,我想使用热键打开它。例如 Ctrl + 打开表单。所以我现在得到了处理 globalkeylistener 的代码,但看起来我实现它失败了。它做了一个 while 循环来防止它关闭程序,我尝试使用 kbh_OnKeyPressed 方法从用户那里获取输入。
我尝试用这种方式实现它:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Globalkey
{
static class Program
{
[DllImport("user32.dll")]
private static extern bool RegisterHotkey(int id, uint fsModifiers, uint vk);
private static bool lctrlKeyPressed;
private static bool f1KeyPressed;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LowLevelKeyboardHook kbh = new LowLevelKeyboardHook();
kbh.OnKeyPressed += kbh_OnKeyPressed;
kbh.OnKeyUnpressed += kbh_OnKeyUnpressed;
kbh.HookKeyboard();
while(true) { }
}
private static void kbh_OnKeyUnpressed(object sender, Keys e)
{
if (e == Keys.LControlKey)
{
lctrlKeyPressed = false;
Console.WriteLine("CTRL unpressed");
}
else if (e == Keys.F1)
{
f1KeyPressed = false;
Console.WriteLine("F1 unpressed");
}
}
private static void kbh_OnKeyPressed(object sender, Keys e)
{
if (e == Keys.LControlKey)
{
lctrlKeyPressed = true;
Console.WriteLine("CTRL pressed");
}
else if (e == Keys.F1)
{
f1KeyPressed = true;
Console.WriteLine("F1 pressed");
}
CheckKeyCombo();
}
static void CheckKeyCombo()
{
if (lctrlKeyPressed && f1KeyPressed)
{
Application.Run(new Form1());
}
}
}
}
【问题讨论】:
-
只是忘了说我想在程序运行的时候打开它,所以“ctrl +
-
只要在keydown事件中捕捉到这个组合键,然后调用表单
-
它必须是全局的,这意味着我可以在程序不集中时访问热键
-
那就别再看了,SetWindowsHookEx 来救场了
标签: c# forms hotkeys global-hotkey