如何在C#中将控制台应用程序窗口置于最前面(特别是在运行Visual Studio调试器时)?
答案 0 :(得分:16)
这很黑,很可怕,但它对我有用(谢谢,pinvoke.net!):
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
public class Test
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
public static void Main()
{
string originalTitle = Console.Title;
string uniqueTitle = Guid.NewGuid().ToString();
Console.Title = uniqueTitle;
Thread.Sleep(50);
IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
if (handle == IntPtr.Zero)
{
Console.WriteLine("Oops, cant find main window.");
return;
}
Console.Title = originalTitle;
while (true)
{
Thread.Sleep(3000);
Console.WriteLine(SetForegroundWindow(handle));
}
}
}
答案 1 :(得分:7)
这就是我要做的。
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public void BringConsoleToFront()
{
SetForegroundWindow(GetConsoleWindow());
}
答案 2 :(得分:0)
获取两个监视器(至少)并在辅助监视器中打开VisualStudio。从VisualStudio中运行应用程序时,默认情况下它将在主监视器上启动。由于它是最后一个要打开的应用程序,它从顶部开始并转换到VisualStudio不会影响它。无论如何都适合我。
如果你还没有第二台显示器,恕我直言,你应该。