SetConsoleMode fails with zero, lasterror = 0

回眸只為那壹抹淺笑 提交于 2019-12-05 11:26:30

Make sure the checkbox "Use legacy console" near the bottom of the console properties is not set:

If you do not see this checkbox, then you are probably using a too old version of Windows.

You can manipulate this checkbox programmatically using the registry key HKCU\Console\ForceV2 as explained in this answer.

Ok. It was a duplicate - sort of. In the answers to the question, referred to by Gusman, SetConsoleMode() and ENABLE_VIRTUAL_TERMINAL_PROCESSING? (that I couldn't find, but should have) - this functionality is only available on Windows 10 (and further... according to Tamás Deme 'tomzorz', only on or after Windows 10 AU), despite Microsoft's claim that it is available on Windows 2000 "and later".

So, the answer is: it doesn't work, and won't except on Windows 10, which is a dead end until Windows 7 has been removed from the planet, and there's no chance it will have to pass QC on Windows 7.

By that time, Console applications will be forbidden by law.

More error checking is needed.

private static readonly IntPtr InvalidHandle = new IntPtr(-1);

handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (handle == InvalidHandle) {
    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
if (!GetConsoleMode(handle, out uint mode)) {
    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(handle, mode)) {
    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!