我正在尝试让应用程序获取用户单击的窗口的鼠标单击位置和标题(名称)。 对于Ex。如果我点击任务栏中打开的outlook,那么我需要将应用程序名称存储为数据库中的“Microsoft Outlook”。
提前致谢....
答案 0 :(得分:3)
检查此代码:How to get active window handle and title
命名空间:
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
方法:
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
电话:
// get handle
IntPtr handle = GetForegroundWindow();
// get title
const int count = 512;
var text = new StringBuilder(count);
if (GetWindowText(handle, text, count) > 0)
{
MessageBox.Show(text.ToString());
}
我几次使用这段代码。真的很容易使用。你可以设置一个每10ms启动一次的计时器。节省2个变量。一个是活动窗口,另一个是最后一个窗口。在伪代码中说:如果是newWindow!= oldWindow - > listView.Add(窗口)。
看起来像这样:
public partial class Form1 : Form
{
// DECLARE GLOBALS //
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string oldWindow = "";
public static string currentWindow = "";
// TIMER EVENT //
private void timerCheckFocus_Tick(object sender, EventArgs e)
{
// get handle
IntPtr handle = GetForegroundWindow();
// get title
const int count = 512;
var currentWindow = new StringBuilder(count);
if (currentWindow.ToString() != oldWindow)
{
// add your window to a listView //
oldWindow = currentWindow.ToString();
}
}
答案 1 :(得分:1)
你可以导入user32.dll
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern IntPtr GetForegroundWindow();
然后例如使用计时器查找活动的应用程序 process.MainWindowTitle为您提供当前窗口/应用程序的名称。
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
IntPtr activeWindow = GetForegroundWindow();
List<String> strListProcesses = new List<string>();
foreach (Process process in Process.GetProcesses())
{
try
{
if (activeWindow == process.MainWindowHandle)
{
newApplication = process.MainWindowTitle;
}
}
catch (System.ComponentModel.Win32Exception ex)
{
}
}
}