Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bring a console window to front in c#

Tags:

c#

window

console

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

like image 980
yoyoyoyosef Avatar asked Oct 17 '08 19:10

yoyoyoyosef


2 Answers

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));
        }
    }
}
like image 192
Jon Skeet Avatar answered Oct 07 '22 18:10

Jon Skeet


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()); 
}
like image 18
ryanb9 Avatar answered Oct 07 '22 19:10

ryanb9