在 C# 中将控制台窗口放在前面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/213480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:24:19  来源:igfitidea点击:

bring a console window to front in c#

c#consolewindow

提问by yoyoyoyosef

How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?

如何将控制台应用程序窗口置于 C# 中(尤其是在运行 Visual Studio 调试器时)?

采纳答案by Jon Skeet

It's hacky, it's horrible, but it works for me (thanks, pinvoke.net!):

它很hacky,很可怕,但它对我有用(谢谢,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));
        }
    }
}

回答by tvanfosson

Get two monitors (at least) and open VisualStudio in the secondary monitor. When you run your app from within VisualStudio it will start up by default on the primary monitor. Since it's the last app to be opened, it starts on top and changing over to VisualStudio doesn't affect it. Works for me anyway.

获取两个监视器(至少)并在辅助监视器中打开 VisualStudio。当您从 VisualStudio 中运行您的应用程序时,它会默认在主监视器上启动。因为它是最后一个打开的应用程序,所以它从顶部开始,切换到 VisualStudio 不会影响它。反正对我有用。

If you don't already have a second monitor, IMHO, you should.

如果你还没有第二台显示器,恕我直言,你应该。

回答by ryanb9

This is what I would do.

这就是我要做的。

[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()); 
}