bring a console window to front in c#

后端 未结 3 1883
名媛妹妹
名媛妹妹 2020-12-03 05:50

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

相关标签:
3条回答
  • 2020-12-03 06:16

    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()); 
    }
    
    0 讨论(0)
  • 2020-12-03 06:28

    It's hacky, it's horrible, but it works for me (thanks, 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));
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 06:38

    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.

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

    0 讨论(0)
提交回复
热议问题