获取当前窗口的名称

时间:2013-01-15 20:45:50

标签: c#

我想知道如何在C#中打开当前窗口的名称。 我已经看了一眼,但是我的问题还没有解决,我希望stackoverflow可以提供帮助。

我会想到像

这样的例子
String currentWindow = Window.Current.toString();

感谢。

2 个答案:

答案 0 :(得分:3)

这是一个片段,可以达到我之前很久以前从作者那里获得的预期效果,所以这可能是重复的。但非如此,这是片段:

private static string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();
    return GetWindowText(handle, buff, nChars) > 0 ? buff.ToString() : null;
}

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

使用示例:

string activeWindowTitle = GetActiveWindowTitle() ?? "Unknown Window";

使用platform invoke调用GetForegroundWindow,它将返回当前前景窗口的句柄。然后,您可以将句柄传递给GetWindowText函数,该函数低,并且会返回窗口标题。

答案 1 :(得分:1)

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

导入,然后像这样使用;

int CharacterMap = 256;
StringBuilder StringInput = new StringBuilder(CharacterMap);
IntPtr Window = GetForegroundWindow();
String WindowTitle = GetWindowText(CharactrMap,StringInput,Window) > 0 ? StringInput.ToString() null;

没有注意到上面的帖子。 Woops! d: