Pergunta

Como posso trazer uma janela de aplicativo de console para a frente em C# (especialmente ao executar o depurador do Visual Studio)?

Foi útil?

Solução

É hacky, é horrível, mas funciona para mim (obrigado, 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));
        }
    }
}

Outras dicas

É isso que eu faria.

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

Obtenha dois monitores (pelo menos) e abra o VisualStudio no monitor secundário. Quando você executa seu aplicativo no VisualStudio, ele será iniciado por padrão no monitor primário. Como é o último aplicativo a ser aberto, ele começa no topo e mudando para o VisualStudio não o afeta. Funciona para mim de qualquer maneira.

Se você ainda não tem um segundo monitor, IMHO, você deveria.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top