So I have a C# Console Application with a Form, which I want to open using hotkeys. Let's say for example Ctrl + < opens the form. So I got the code to handle a globalkeylistener now, but it looks like I failed by implementing it. It made a while loop to prevent it from closing the program and I tryed to get an input from the user with the kbh_OnKeyPressed method.
I tryed to implement it this way:
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());
}
}
}
}
What you need is a Lowlevel Keyboard Hook.
This could look somewhat like this:
To implement it, you could use something like this:
The event could be handled like that:
For actual understanding, i would recommend you to have a read on P/Invoke. That is making use of the unmanaged APIs that windows provides.
For a full list of P/Invoke possibilites, pinvoke.net is a great source.
For better understanding in general, The official MSDN Website is a good source, too.
EDIT:
It seems like you're actually using a Console Application, not a WinForm one. In that case, you have to run the program a bit differently:
The Run() method of the Application Class starts a standard loop for your application. This is necessary for the Hook to work, because a mere Console Application without this loop is, as far as I know, not capable of triggering those global key events.
Using this implementation, pressing and releasing the defined keys gives the following output:
Note: I obviously replaced
Application.Run(new Form1());
in the
CheckKeyCombo()
method withConsole.WriteLine("KeyCombo pressed");