2 # PowerShell script for controlling the console QuickEdit and InsertMode flags.
4 # Turn QuickEdit off to interact with mouse-driven console programs.
8 # powershell .\ConinMode.ps1 [Options]
12 # -InsertMode [on/off]
17 [ValidateSet("on", "off")][string] $QuickEdit,
18 [ValidateSet("on", "off")][string] $InsertMode,
23 [DllImport("kernel32.dll", SetLastError = true)]
24 public static extern IntPtr GetStdHandle(int nStdHandle);
26 [DllImport("kernel32.dll", SetLastError = true)]
27 public static extern uint GetConsoleMode(
28 IntPtr hConsoleHandle,
31 [DllImport("kernel32.dll", SetLastError = true)]
32 public static extern uint SetConsoleMode(
33 IntPtr hConsoleHandle,
36 public const int STD_INPUT_HANDLE = -10;
37 public const int ENABLE_INSERT_MODE = 0x0020;
38 public const int ENABLE_QUICK_EDIT_MODE = 0x0040;
39 public const int ENABLE_EXTENDED_FLAGS = 0x0080;
42 $WinAPI = Add-Type -MemberDefinition $signature `
43 -Name WinAPI -Namespace ConinModeScript `
47 $ret = $WinAPI::GetStdHandle($WinAPI::STD_INPUT_HANDLE)
49 throw "error: cannot get stdin"
54 function GetConsoleMode {
57 $ret = $WinAPI::GetConsoleMode($conin, [ref]$mode)
59 throw "GetConsoleMode failed (is stdin a console?)"
64 function SetConsoleMode($mode) {
66 $ret = $WinAPI::SetConsoleMode($conin, $mode)
68 throw "SetConsoleMode failed (is stdin a console?)"
72 $oldMode = GetConsoleMode
74 $doingSomething = $false
76 if ($PSBoundParameters.ContainsKey("Mode")) {
78 $doingSomething = $true
81 if ($QuickEdit + $InsertMode -ne "") {
82 if (!($newMode -band $WinAPI::ENABLE_EXTENDED_FLAGS)) {
83 # We can't enable an extended flag without overwriting the existing
84 # QuickEdit/InsertMode flags. AFAICT, there is no way to query their
85 # existing values, so at least we can choose sensible defaults.
86 $newMode = $newMode -bor $WinAPI::ENABLE_EXTENDED_FLAGS
87 $newMode = $newMode -bor $WinAPI::ENABLE_QUICK_EDIT_MODE
88 $newMode = $newMode -bor $WinAPI::ENABLE_INSERT_MODE
89 $doingSomething = $true
93 if ($QuickEdit -eq "on") {
94 $newMode = $newMode -bor $WinAPI::ENABLE_QUICK_EDIT_MODE
95 $doingSomething = $true
96 } elseif ($QuickEdit -eq "off") {
97 $newMode = $newMode -band (-bnot $WinAPI::ENABLE_QUICK_EDIT_MODE)
98 $doingSomething = $true
101 if ($InsertMode -eq "on") {
102 $newMode = $newMode -bor $WinAPI::ENABLE_INSERT_MODE
103 $doingSomething = $true
104 } elseif ($InsertMode -eq "off") {
105 $newMode = $newMode -band (-bnot $WinAPI::ENABLE_INSERT_MODE)
106 $doingSomething = $true
109 if ($doingSomething) {
110 echo "old mode: $oldMode"
111 SetConsoleMode $newMode
112 $newMode = GetConsoleMode
113 echo "new mode: $newMode"
115 echo "mode: $oldMode"