【问题标题】:bring a console window to front in c#在 C# 中将控制台窗口置于前面
【发布时间】:2010-09-17 19:52:36
【问题描述】:

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

【问题讨论】:

  • 在什么情况下,为什么要这样做?虽然有合法的案例,但通常这种事情比它的价值更麻烦。

标签: c# console window


【解决方案1】:

这很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));
        }
    }
}

【讨论】:

  • 请不要将它添加到您的代码中,只是为了让它在调试时出现在顶部。
  • @tv - 也许你可以对你的绝对陈述做出解释。我个人认为这是合法且推荐使用的窗口管理功能。这不是最好的 DRY 方法,但稍微重构一下,它是 win32 应用程序开发中的常见做法。这不是 hackey,而是您在桌面上移动窗口的方式。
  • 只是补充一下,如果您希望仅在 Visual Studio 调试器中运行此代码,您可以使用以下内容:if (Debugger.IsAttached == true) { ... }
  • @Marcus:或者最好没有“== true”位;)
  • @JonSkeet .. 与否。随着眼睛年龄的增长,看到 (!MyCondition) 之类的东西变得更容易错过并产生错误。
【解决方案2】:

这就是我会做的。

[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); //restore
【解决方案3】:

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

如果您还没有第二台显示器,恕我直言,您应该这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2012-10-11
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多