C# 控制台应用程序在鼠标单击时冻结
我有一个非常简单的C#控制台应用程序,它显示一些文本和循环,等待输入,直到按下escape键或超时C# 控制台应用程序在鼠标单击时冻结,c#,.net,console,mouseevent,console-application,C#,.net,Console,Mouseevent,Console Application,我有一个非常简单的C#控制台应用程序,它显示一些文本和循环,等待输入,直到按下escape键或超时 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace SampleApp { public static class Program {
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();
}
}
}
这很好,但如果我用鼠标点击控制台应用程序(例如获得焦点),屏幕上的所有活动都会冻结,直到我右键单击或按escape。在此期间,控制台的标题也会更改为“Select AppName”
,前提是“AppName”
是之前的标题
如果我首先右键单击控制台,do{…}while()代码>循环似乎疯了,打印了很多额外的行
因为我没有意识到控制台的这种行为,所以不知道该问什么。这是意料之中的事吗?如果是,我可以改变这种行为吗?如果没有,请提供任何解决办法的建议。根据Hans的上述评论,问题得以解决
听起来你已经激活了控制台窗口的标记和粘贴命令。通常通过系统菜单激活(Alt+空格、编辑、标记/粘贴)。当然,这与代码无关。
显然,出于某种原因,在控制台默认设置(Alt+Space、默认值、选项、编辑选项、快速编辑模式)中设置了快速编辑模式。取消选中该选项解决了问题。我觉得您已经以某种方式激活了控制台窗口的标记和粘贴命令。通常通过系统菜单激活(Alt+空格、编辑、标记/粘贴)。当然,这与代码无关。谢谢@HansPassant。我不会想到的。显然,出于某种原因,在控制台默认设置(Alt+Space、默认值、选项、编辑选项、快速编辑模式)中设置了快速编辑模式。取消勾选解决了问题。你应该发表你的评论作为回答。
//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;
}
}