如何检测Windows是第一次创建并关闭(未最小化)?我需要记录创建和关闭属于进程的新窗口的时间。
我目前的实施是:
public partial class Form2 : Form
{
WinEventDelegate dele2 = null;
delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
private const int WINEVENT_INCONTEXT = 4;
private const int WINEVENT_OUTOFCONTEXT = 0;
private const int WINEVENT_SKIPOWNPROCESS = 2;
private const int WINEVENT_SKIPOWNTHREAD = 1;
private const uint EVENT_SYSTEM_FOREGROUND = 3;
private const uint EVENT_SYSTEM_DESTROY = 0x8001;
private const uint EVENT_OBJECT_CREATE = 0x8000;
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
public Form2()
{
InitializeComponent();
dele2 = new WinEventDelegate(WinEventProcDestory);
SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_SYSTEM_DESTROY, IntPtr.Zero, dele2, 0, 0, WINEVENT_OUTOFCONTEXT);
}
private string GetActiveWindowTitle()
{
const int nChars = 256;
IntPtr handle = IntPtr.Zero;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
private String GetProcessName(IntPtr hwnd)
{
uint pid;
IntPtr ptr = GetWindowThreadProcessId(hwnd, out pid);
Process p = Process.GetProcessById((int)pid);
return p.ProcessName;
}
public void WinEventProcDestory(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
String windowTitle = GetActiveWindowTitle();
this.dataGridView2.Rows.Add(windowTitle, DateTime.Now, "-");
}
}
正如您在实现中所看到的,我正在将每个事件记录到数据网格中,并且一旦启动应用程序,我就会为此或我打开的任何其他应用程序获取10个以上的事件。我只想到一个。
或者更好的方法是使用Java(JNI)吗?对所有解决方案开放。
提前致谢!