📅  最后修改于: 2023-12-03 15:13:49.012000             🧑  作者: Mango
GetForegroundWindow()
是C#中常用的Windows API函数之一,用于获取当前活动窗口的句柄。它属于user32.dll动态链接库,定义如下:
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
这个函数的作用是:获取当前激活窗口的句柄,即正在与用户交互的窗口,通常是最前面的窗口。
示例代码如下:
IntPtr hwnd = GetForegroundWindow();
string windowText = GetWindowText(hwnd);
Console.WriteLine(windowText);
在这个例子中,我们调用了另一个函数GetWindowText()
,用于获取窗口文本内容。注意:GetWindowText()
是另一个Windows API函数,也需要定义与引入才能使用。
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
如果窗口没有标题栏,返回的文本内容为空字符串。
使用GetForegroundWindow()
函数,可以实现如下功能:
下面的示例代码演示了如何获取当前活动窗口的标题栏,并将其复制到剪贴板:
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
class Program
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
public static extern bool SetWindowText(IntPtr hWnd, string text);
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
static extern bool CloseClipboard();
[DllImport("user32.dll")]
static extern bool EmptyClipboard();
[DllImport("user32.dll")]
static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
[DllImport("user32.dll")]
static extern int MessageBox(IntPtr hwnd, string text, string title, uint type);
const int WM_KEYDOWN = 0x0100;
const int WM_KEYUP = 0x0101;
const int WM_SYSKEYDOWN = 0x0104;
const int WM_SYSKEYUP = 0x0105;
const int VK_CONTROL = 0x11;
const int VK_C = 0x43;
static void Main(string[] args)
{
string lastTitle = "";
while (true)
{
IntPtr hwnd = GetForegroundWindow();
StringBuilder sbTitle = new StringBuilder(256);
GetWindowText(hwnd, sbTitle, sbTitle.Capacity);
string title = sbTitle.ToString();
if (title != lastTitle)
{
lastTitle = title;
Console.WriteLine(title);
}
if (Control.ModifierKeys == Keys.Control && Keyboard.IsKeyDown(Keys.C))
{
OpenClipboard(IntPtr.Zero);
EmptyClipboard();
SetClipboardData(13, Marshal.StringToHGlobalUni(title));
CloseClipboard();
Console.WriteLine("Title copied to clipboard");
}
System.Threading.Thread.Sleep(50);
}
}
}
这个简单的程序会不停地监测当前活动窗口,如果窗口标题栏发生变化,就输出新的标题栏。如果用户在按住Ctrl键的同时按下C键,则会将当前窗口的标题栏复制到剪贴板中。