c# - 如何让C#控制台应用程序始终走在前面?

标签 c# console

如何确保我的 C# 控制台应用程序始终位于前面? e.i.如果有人在控制台之外单击,我如何检测到控制台已失去焦点并将其带回到前面? 我有这个 C# 控制台应用程序,正在等待用户扫描条形码,如果由于某种原因有人单击控制台窗口,则条形码数据将“丢失”。 我看了一下发布在另一个线程上的这段代码;但是,我似乎无法让它为我工作: bring a console window to front in c# 感谢@ILan,这段代码将控制台保持在所有窗口的顶部,但它没有设置“焦点”来继续捕获传入的数据。

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

最佳答案

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

有关如何在您的应用程序不是附加到控制台的应用程序的情况下获取句柄的完整答案,请参阅 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();
    }
}

关于c# - 如何让C#控制台应用程序始终走在前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53026524/

相关文章:

c# - 生成 docx 文件的库 (Open XML)

c# - 如何使用来自不同项目的模型类通过反射提供程序创建 WCF 数据服务 OData?

c# - 如何中止多个线程?

emacs - 如何在控制台窗口中启动 Emacs?

javascript - Node.js console.log 与 console.info

c# - .NET 公共(public)静态变量的 "lifespan"?

c# - 如何将 tsharks 输出实时传输到 C# 程序

Code::Blocks 不显示任何输出

powershell - 如何以编程方式将Powershell背景色设置为RGB值

python - Windows 上没有控制台的 Cython