bring a console window to front in c#

后端 未结 3 1920
名媛妹妹
名媛妹妹 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: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));
            }
        }
    }
    

提交回复
热议问题