Jor*_*ira 162
有关如何使用完整源代码执行此操作的示例:
http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
编辑 @Doug McClean评论更好的正确性.
小智 17
如果你在谈论WPF,那么使用:
Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
Run Code Online (Sandbox Code Playgroud)
基于GetForegroundWindow 函数| 微软文档:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);
private string GetCaptionOfActiveWindow()
{
var strTitle = string.Empty;
var handle = GetForegroundWindow();
// Obtain the length of the text
var intLength = GetWindowTextLength(handle) + 1;
var stringBuilder = new StringBuilder(intLength);
if (GetWindowText(handle, stringBuilder, intLength) > 0)
{
strTitle = stringBuilder.ToString();
}
return strTitle;
}
Run Code Online (Sandbox Code Playgroud)
它支持 UTF8 字符。
小智 5
循环Application.Current.Windows[]
并找到带有 的那个IsActive == true
。
归档时间: |
|
查看次数: |
114222 次 |
最近记录: |