在C#中将控制台窗口置于前台

14

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


你为什么想要在什么情境下做这件事,这个背后的原因是什么?虽然有一些合法的情况需要这么做,但通常这种做法会带来更多的麻烦而不值得。 - ICR
3个回答

19

虽然有点糟糕,但对我来说很有效(感谢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));
        }
    }
}

请不要仅仅为了在调试时将其显示在顶部而将此内容添加到您的代码中。 - tvanfosson
4
也许你可以解释一下你的绝对说法。就我个人而言,我认为这是窗口管理功能的一个合法且推荐的用法。虽然这不是最好的DRY方法,但稍加重构后,在win32应用程序开发中这是一种常见做法。这不是hackey,而是移动桌面窗口的方式。 - Marcus Pope
只是补充一下,如果你想在 Visual Studio 调试器中运行此代码,可以使用以下代码:if (Debugger.IsAttached == true) { ... } - Marcus Pope
9
@Marcus: 或者最好不要带上 "== true" 那一段 ;) - Jon Skeet
3
@JonSkeet ..或者不做。随着年龄的增长,像(!MyCondition)这样的东西变得更容易被忽略并导致错误。 - StingyJack
@StingyJack:我想我们不得不就这个问题保持不同意见。特别地,用等宽字体比你在那里写的更清晰。 - Jon Skeet

19

这就是我的做法。

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

很好 - 除了我需要添加以下内容: [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 以及 ShowWindow(hWnd, 9); //恢复 - AndrewFreese

-4

准备两个显示器(至少)并在辅助显示器上打开VisualStudio。当您从VisualStudio中运行应用程序时,它将默认在主显示器上启动。由于它是最后一个被打开的应用程序,因此它始终在顶部,并且切换到VisualStudio不会影响它。对我来说很有效。

如果您还没有第二个显示器,我认为您应该考虑购买一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接