控制台应用程序在单击鼠标时冻结



我有一个非常简单的 C# 控制台应用程序,它显示一些文本和循环等待输入,直到按下转义键或提供超时期限。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace SampleApp
{
    public static class Program
    {
        public static void Main (string [] args)
        {
            var key = new ConsoleKeyInfo();
            var watch = Stopwatch.StartNew();
            var timeout = TimeSpan.FromSeconds(5);
            Console.WriteLine("Press escape to return to the previous screen...");
            Console.WriteLine();
            do
            {
                Console.WriteLine("This screen will automatically close in " + ((timeout + TimeSpan.FromSeconds(1)) - watch.Elapsed).ToString(@"hh:mm:ss") + ".");
                if (Console.KeyAvailable) { key = Console.ReadKey(true); }
                else { Thread.Sleep(TimeSpan.FromSeconds(0.10D)); }
            }
           while ((key.Key != ConsoleKey.Escape) && (timeout > (watch.Elapsed - TimeSpan.FromSeconds(0.5D))));
            watch.Stop();
        }
    }
}

这工作正常,但是如果我用鼠标单击控制台应用程序(例如获得焦点),屏幕上的所有活动都会冻结,直到我右键单击或按 Esc 键。在此期间,控制台的标题也会更改为"Select AppName"假设"AppName"是之前的标题。

如果我先右键单击控制台,do {...} while ();循环似乎变得疯狂并打印了很多额外的行。

由于我不知道控制台的这种行为,因此不确定要问什么。这是意料之中的吗?如果是这样,我可以更改此行为吗?如果没有,任何解决方法建议将不胜感激。

这个问题是用汉斯上面的评论解决的。

在我看来,您以某种方式激活了控制台窗口的"标记"和"粘贴"命令。通常通过系统菜单激活(Alt + 空格键、编辑、标记/粘贴)。当然,这与这段代码没有任何关系。

显然,由于某种原因,快速编辑模式是在控制台默认值(Alt + 空格、默认值、选项、编辑选项、快速编辑模式)中设置的。取消选中已解决问题。

//call this class to disable quick edit mode.
public static void Main()
{
//disable console quick edit mode
 DisableConsoleQuickEdit.Go();
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

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;
    }
}

最新更新