我试图获取我点击的每个窗口的名称。我有工作代码,但它使用系统计时器而不是表单上的计时器。我将发布代码,以便它的eaiser看看我做错了什么。它也没有让我回到我的文本框,我想我需要将它带入功能。
继承人Dll导入和变量
private static string LastActiveWindow = "";
private static string ActiveWindowName = "";
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWind, StringBuilder lpString, int nMaxCount);
然后我让我的计时器每秒运行10次,这将运行活动窗口功能:
private void TimerActiveWindow_Tick(object sender, EventArgs e)
{
ActiveWindow();
}
private static void ActiveWindow(object Obj, EventArgs e)
{
IntPtr hwnd = GetForegroundWindow();
const int Capacity = 512;
var text = new StringBuilder(Capacity);
try
{
if (GetWindowText(hwnd, text, Capacity) > 0)
{
if (ActiveWindowName != text.ToString())
{
if (!LastActiveWindow.Equals(text.ToString()))
{
// TxtBody.text += "<br><font color = purple> Current Window - [" + text.ToString() + "]</font><br>";
LastActiveWindow = text.ToString();
MessageBox.Show(text.ToString());
}
}
}
}
catch { }
}
唯一的区别是我的程序使用系统计时器的计时器看起来像这样
System.Timers.Timer TimerActiveWindow = new System.Timers.Timer();
TimerActiveWindow.Elapsed += new ElapsedEventHandler(Program.ActiveWindow);
TimerActiveWindow.AutoReset = true;
TimerActiveWindow.Interval = 100;