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

Himanshu picture Himanshu · Dec 1, 2012 · Viewed 11.7k times · Source

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.

Please guide.

Answer

Patrick from NDepend team picture Patrick from NDepend team · Apr 19, 2016

For those like me that like no-brainer code to copy/paste, here is the code inspired from the accepted answer:

using System;
using System.Runtime.InteropServices;

static class DisableConsoleQuickEdit {

   const uint ENABLE_QUICK_EDIT = 0x0040;

   // STD_INPUT_HANDLE (DWORD): -10 is the standard input device.
   const int STD_INPUT_HANDLE = -10;

   [DllImport("kernel32.dll", SetLastError = true)]
   static extern IntPtr GetStdHandle(int nStdHandle);

   [DllImport("kernel32.dll")]
   static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);

   [DllImport("kernel32.dll")]
   static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);

   internal static bool Go() {

      IntPtr consoleHandle = GetStdHandle(STD_INPUT_HANDLE);

      // get current console mode
      uint consoleMode;
      if (!GetConsoleMode(consoleHandle, out consoleMode)) {
         // ERROR: Unable to get console mode.
         return false;
      }

      // Clear the quick edit bit in the mode flags
      consoleMode &= ~ENABLE_QUICK_EDIT;

      // set the new mode
      if (!SetConsoleMode(consoleHandle, consoleMode)) {
         // ERROR: Unable to set console mode
         return false;
      }

      return true;
   }
}