Question

Comment afficher une fenêtre d'application console en C # (en particulier lors de l'exécution du débogueur Visual Studio)?

Était-ce utile?

La solution

C'est hacky, c'est horrible, mais ça marche pour moi (merci, 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));
        }
    }
}

Autres conseils

C'est ce que je ferais.

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

Obtenez deux moniteurs (au moins) et ouvrez VisualStudio dans le moniteur secondaire. Lorsque vous exécutez votre application à partir de VisualStudio, elle démarre par défaut sur le moniteur principal. Comme c'est la dernière application à être ouverte, elle commence par le haut et le passage à VisualStudio ne l'affecte pas. Ça marche pour moi quand même.

Si vous ne possédez pas déjà un deuxième moniteur, à mon humble avis, vous devriez le faire.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top