In a C# Console app, pressing the Pause key freezes the display output. Can I disable that?
I was hoping for a handler like the Console.CancelKeyPress
event that handles Ctrl+C input.
In a C# Console app, pressing the Pause key freezes the display output. Can I disable that?
I was hoping for a handler like the Console.CancelKeyPress
event that handles Ctrl+C input.
Every once in a while a request comes up for hooking keys from a console program. The standard events like CTRL_C_EVENT
and CTRL_CLOSE_EVENT
do not include the Pause-event. I've tried doing so using a background thread, but I don't seem to manage. However, there's a not-so-hard workaround: use an extra process.
Download this easy-to-use global keyboard hook for C#. Then, when you open that project, take the following code and put it in the Form1.cs:
public partial class Form1 : Form {
globalKeyboardHook globalKeyboardHook = new globalKeyboardHook();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
globalKeyboardHook.HookedKeys.Add(Keys.Pause);
globalKeyboardHook.KeyDown += new KeyEventHandler(globalKeyboardHook_KeyDown);
globalKeyboardHook.KeyUp += new KeyEventHandler(globalKeyboardHook_KeyUp);
}
void globalKeyboardHook_KeyUp(object sender, KeyEventArgs e)
{
// remove this when you want to run invisible
lstLog.Items.Add("Up\t" + e.KeyCode.ToString());
// this prevents the key from bubbling up in other programs
e.Handled = true;
}
void globalKeyboardHook_KeyDown(object sender, KeyEventArgs e)
{
// remove this when you want to run without visible window
lstLog.Items.Add("Down\t" + e.KeyCode.ToString());
// this prevents the key from bubbling up in other programs
e.Handled = true;
}
}
Then, the rest becomes trivial:
I tried the above myself and it works.
PS: I don't mean that there isn't a possible way straight from a Console program. There may very well be, I just didn't find it, and the above global keyhook library didn't work from within a Console application.
It's not necessary to attach an hook for this. In your case @PeteVasi, you can modify the console mode to capture Ctrl+C, Ctrl+S, etc... events that are not normally possible to capture.