活动窗口标题

问题描述 投票:0回答:1

我想获取 C# 控制台应用程序中当前活动窗口的标题字符串。

我的下面的代码就是这样做的。然而,只有当我逐行缓慢地调试代码时,它才有效。当我刚开始运行时,

while
似乎进入了无限循环。然而,如果没有
while
循环,首先就找不到窗口标题(因此不会写入控制台)。

怎么了?以及如何解决?

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);

    static void Main(string[] args)
    {
        IntPtr handle = GetForegroundWindow();
        const int nChars = 256;
        System.Text.StringBuilder Buff = new System.Text.StringBuilder(nChars);
        while (GetWindowText(handle, Buff, nChars) <= 0)
        {
            // Wait until GetWindowText returns a positive value
        }
        Console.WriteLine(Buff.ToString());
    }
}
c# user32
1个回答
0
投票

为什么会有循环?如果你想连续检查活动窗口标题,你也想将

IntPtr handle = GetForegroundWindow();
移动到循环中,而且我想你需要放慢一点速度。无论如何,这对我来说效果很好:

using System.Runtime.InteropServices;
using System.Text;

class Program
{
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
    
    static void Main(string[] args)
    {        
        // You may want to add a circuit breaker here, e.g. when a key is storked
        while (true)
        {
            Console.WriteLine(GetActiveWindowTitle());
            Thread.Sleep(300);
        }        
    }

    public static string GetActiveWindowTitle()
    {
        const int nChars = 256;
        StringBuilder buffer = new StringBuilder(nChars);
        IntPtr handle = GetForegroundWindow();        

        return GetWindowText(handle, buffer, nChars) > 0 ? buffer.ToString() : string. Empty;
    }
}

附注这是一个非常有趣的相关项目:https://github.com/dotnet/pinvoke

© www.soinside.com 2019 - 2024. All rights reserved.