In a C# Console app, the Pause key freezes the display output. Can I disable that?

帅比萌擦擦* 提交于 2020-01-13 03:54:13

问题


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.


回答1:


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:

  1. Change your program to start the above program and than run normally
  2. Try to type the pause key
  3. It'll be caught by the other program
  4. Your program will NOT be paused.

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.




回答2:


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.

See my answer to a similar question here.



来源:https://stackoverflow.com/questions/9950863/in-a-c-sharp-console-app-the-pause-key-freezes-the-display-output-can-i-disabl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!