Earlier today I was struck by pecular problem with the application I had been working on for PEAK challange, which is Neumont‘s bi-annual student competition where everyone who signs up has a chance to show off projects they or a team of theirs has done over the last year. It’s sort of a science fair concept put on by the Neumont Student Government (USG).
But… that aside, hooking Win32 DLL’s.
Alright, the program I’m working on runs in the background of the computer and records when your active based off of the mouse movement and keyboard input. This program will then automatically fill out a time sheet based off of the time you were active on your computer without the user having to do anything. The problem I was running into was, if you had been inactive on your computer for, lets say, 15 minutes (It’s configurable), when you come back it will ask you if you were working away from your computer or if you were taking a break or what. It then records the times and dissipates into the background. In order for this to work effectively however, I needed the popup box to override all the current active windows and be on top of them. This presents a problem, because .NET applications are built to be internal and well ‘packaged’ into their own little container that prevents them from causing issues with other applications. Normally this is a good thing, but for my task I needed to FORCE my window overtop of all the others when it wasn’t in focus. After several frustrating hours of trial and error, and countless forums, semi-related tutorials I finally decided that I had to hook into the User32.dll functions to get the behavior I needed, namely, forcing my dialog box on top of any and all other windows.
So, here is the rather short final set of methods that can be used to set focus to any windows form over all the other applications using unmanaged Win32 calls.
//CLR wrapping of unmanaged functions public static int GetWindowHandle(System.String WindowTitle) { //a return value of 0 indicates that the function did not find the window return FindWindow(null, WindowTitle); } public static void SetWindowFocus(int windowHandle) { SetForegroundWindow(windowHandle); } #region Unmanaged USER32 Functions //DLL external functions hitting User32.dll [DllImport("User32.dll")] private static extern Int32 FindWindow(String lpClassName, String lpWindowName); [DllImport("User32.dll")] private static extern Boolean SetForegroundWindow(Int32 hWnd); #endregion
Pingback: Paul Rohde » PEAK Challange