首页 > 解决方案 > How to make C# console application to always be in front?

问题描述

How can I ensure my C# console application is always in front? e.i. if a person clicks away from the console, how can I detect that the console has lost the focus an bring it back to front? I have this C# console application that is waiting for users to scan bar codes, if for some reason someone clicks away from the console window then the barcode data will be "lost". I took a look at this code posted on another thread;however, I can not seem to get this to work for me: bring a console window to front in c# This code thanks to @ILan keeps the console ontop of all windows, but it does not set the "focus" to keep capturing the incoming data.

   class Program
{
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, 
                                    IntPtr hWndInsertAfter, 
                                    int X, 
                                    int Y, 
                                    int cx, 
                                    int cy, 
                                    uint uFlags);
    static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    const uint SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_SHOWWINDOW = 0x0040;

    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    static void Main()
    {
        IntPtr handle = GetConsoleWindow();
        SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        Console.WriteLine($"Hello handle: {handle}");
        Console.ReadLine();
    }
}

标签: c#console

解决方案


如果应用程序是附加到控制台的应用程序,则以下将完成这项工作。

有关在您的应用程序不是附加到控制台的应用程序的情况下如何获取句柄的完整答案,请参阅https://stackoverflow.com/a/28616832/2370138

class Program
{
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, 
                                    IntPtr hWndInsertAfter, 
                                    int X, 
                                    int Y, 
                                    int cx, 
                                    int cy, 
                                    uint uFlags);
    static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    const uint SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_SHOWWINDOW = 0x0040;

    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    static void Main()
    {
        IntPtr handle = GetConsoleWindow();
        SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        Console.WriteLine($"Hello handle: {handle}");
        Console.ReadLine();
    }
}

推荐阅读