Search code examples
c#console-application

How to programmatic disable C# Console Application's Quick Edit mode?


I've tried several solutions found, like the one ->

http://www.pcreview.co.uk/forums/console-writeline-hangs-if-user-click-into-console-window-t1412701.html

But, I observed that mode in GetConsoleMode(IntPtr hConsoleHandle, out int mode) will be different for different console app. It is not constant.

Can I disable mouse clicks (right/left buttons) on a console application to achieve the same scenario. I found that it can be done with IMessageFilter but only for Window Form Application and not for console application.


Solution

  • If you want to disable quick edit mode, you need to call GetConsoleMode to get the current mode. Then clear the bit that enables quick edit, and call SetConsoleMode. Assuming you have the managed prototypes for the unmanaged functions, you would write:

    const int ENABLE_QUICK_EDIT = 0x0040;
    
    IntPtr consoleHandle = GetConsoleWindow();
    UInt32 consoleMode;
    
    // get current console mode
    if (!GetConsoleMode(consoleHandle, out consoleMode))
    {
        // Error: Unable to get console mode.
        return;
    }
    
    // Clear the quick edit bit in the mode flags
    mode &= ~ENABLE_QUICK_EDIT;
    
    // set the new mode
    if (!SetConsoleMode(consoleHandle, consoleMode))
    {
        // ERROR: Unable to set console mode
    }
    

    If you want to disable mouse input, you want to clear the mouse input bit.

    const int ENABLE_MOUSE_INPUT = 0x0010;
    
    mode &= ~ENABLE_MOUSE_INPUT;