Turn off Windows 10 console “Mark” mode from my application

风流意气都作罢 提交于 2021-02-10 06:15:57

问题


I've got a console application written in Python. Windows 10 console's "Mark" mode is frustrating me to no end as users accidentally click in the application while doing something as simple as switching windows. Do I have any way to control and stop this?

For those who are unaware of Mark mode, it is when a user selects some text in the console window. When the program next writes to stdout, the entire program is paused, which is very very very annoying.

Thanks!


回答1:


Automatic "Mark" mode using the mouse in windows 10, is "Quick Edit" mode from prior versions. I believe the only difference is that it is now on by default. Quick Edit Mode can be enabled/disabled from code:

import time
import win32console

ENABLE_QUICK_EDIT_MODE = 0x40
ENABLE_EXTENDED_FLAGS = 0x80


def quick_edit_mode(turn_on=None):
    """ Enable/Disable windows console Quick Edit Mode """
    screen_buffer = win32console.GetStdHandle(-10)
    orig_mode = screen_buffer.GetConsoleMode()
    is_on = (orig_mode & ENABLE_QUICK_EDIT_MODE)
    if is_on != turn_on and turn_on is not None:
        if turn_on:
            new_mode = orig_mode | ENABLE_QUICK_EDIT_MODE
        else:
            new_mode = orig_mode & ~ENABLE_QUICK_EDIT_MODE
        screen_buffer.SetConsoleMode(new_mode | ENABLE_EXTENDED_FLAGS)

    return is_on if turn_on is None else turn_on

quick_edit_enabled = quick_edit_mode()
while True:
    print('Quick edit is %s' % ('on' if quick_edit_enabled else 'off'))
    time.sleep(3)
    quick_edit_enabled = quick_edit_mode(not quick_edit_enabled)



回答2:


I'm a little short on reputation to comment on Stephen's answer so I'm posting a separate answer.

To make this multi-platform/environment friendly add some conditional checks to skip over the code when not running on windows or when no console is attached to the process such as when running inside an IDE or when built via pyinstaller etc:

if os.name == "nt" and sys.stdout.isatty():
    # stephen's code here...

This prevents errors from being raised in several cases. In my opinion you should also add a try/catch-all around the code block since os-implementations of the methods involved are unknown and are known to raise exceptions and be finicky. In the worst case scenario I would rather my code continue to run with QuickEdit enabled than fail because of it.



来源:https://stackoverflow.com/questions/41409727/turn-off-windows-10-console-mark-mode-from-my-application

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