How can I detect whether Windows are created for the first time and closed (not minimised)? I need to log the time a new window which belongs to a process is created and closed.
My current implementation is:
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, "-");
}
}
As you can see in the implementation I'm logging each event to a datagrid and as soon as I start the application I get 10+ events for this or any other application I open. I expected just one.
Alternatively is there a better way to do is with Java (JNI)? Open to all solutions.
Thanks in advance!