public
Created

Window Monitor

  • Download Gist
Form1-EXAMPLE.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace Test
{
public partial class Form1 : Form
{
 
protected override bool ShowWithoutActivation
{
get
{
return true;
}
}
 
public Form1()
{
InitializeComponent();
}
 
const string Process_Communicator = "communicator";
const string WindowClass_CtrlNotifySink = "CtrlNotifySink";
const string WindowClass_VideoParent = "LCC_VideoParent";
const string WindowClass_IMWindow = "IMWindowClass";
 
private WindowMonitor _windowMonitor;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_windowMonitor = new WindowMonitor();
 
_windowMonitor.SelectWindow += LyncSelection;
// Add selections for other IM apps as needed.
// _windowMonitor.SelectWindow += SkypeSelection;
 
_windowMonitor.Activated += _windowMonitor_Activated;
_windowMonitor.Deactivated += _windowMonitor_Deactivated;
_windowMonitor.LocationChanged += _windowMonitor_LocationChanged;
_windowMonitor.Start();
}
 
void LyncSelection(object sender, WindowSelectionEventArgs e)
{
var info = e.ActiveWindow;
if (e.Process.ProcessName == Process_Communicator && info.WindowClass == WindowClass_IMWindow)
{
// I used http://sourceforge.net/projects/windowdetective/ to figure this out.
 
// Get the last CtrlNotifySink that contains a LCC_VideoParent.
var sink = info.ChildWindows.Last(
x => x.WindowClass == WindowClass_CtrlNotifySink &&
x.ChildWindows.Any(y => y.WindowClass == WindowClass_VideoParent));
 
// Check if we got a result.
if (sink == null) return;
 
// Check that the CtrlNotifySink is visible.
if (sink.Style.HasFlag(WindowMonitor.WindowStyles.Visible))
{
// Select the video area so that we get the overlay
// appearing there.
e.Select(sink);
}
}
}
 
void _windowMonitor_LocationChanged(object sender, RectangleEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new EventHandler<RectangleEventArgs>(_windowMonitor_LocationChanged), sender, e);
return;
}
 
var x = e.Rectangle.Right - this.Width;
var y = e.Rectangle.Bottom - this.Height;
this.Left = x;
this.Top = y;
}
 
void _windowMonitor_Deactivated(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new EventHandler(_windowMonitor_Deactivated), sender, e);
return;
}
 
this.Hide();
}
 
void _windowMonitor_Activated(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new EventHandler(_windowMonitor_Activated), sender, e);
return;
}
 
this.Show();
}
}
}
WindowMonitor.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace Test
{
/// <summary>
/// Represents event information about a <see cref="Rectangle"/>.
/// </summary>
class RectangleEventArgs : EventArgs
{
/// <summary>
/// Gets the rectangle.
/// </summary>
/// <value>
/// The rectangle.
/// </value>
public Rectangle Rectangle { get; private set; }
 
/// <summary>
/// Initializes a new instance of the <see cref="RectangleEventArgs" /> class.
/// </summary>
/// <param name="rect">The rect.</param>
public RectangleEventArgs(Rectangle rect)
{
Rectangle = rect;
}
}
 
class WindowSelectionEventArgs : EventArgs
{
/// <summary>
/// Gets the owner process of the window.
/// </summary>
/// <value>
/// The owner process of the window.
/// </value>
public Process Process { get; private set; }
 
/// <summary>
/// Gets the active window.
/// </summary>
/// <value>
/// The active window.
/// </value>
public WindowMonitor.WindowInformation ActiveWindow { get; private set; }
 
/// <summary>
/// Gets the selected window.
/// </summary>
/// <value>
/// The selected window.
/// </value>
public WindowMonitor.WindowInformation SelectedWindow { get; private set; }
 
/// <summary>
/// Initializes a new instance of the <see cref="WindowSelectionEventArgs" /> class.
/// </summary>
/// <param name="activeWindow">The active window.</param>
public WindowSelectionEventArgs(Process process, WindowMonitor.WindowInformation activeWindow)
{
Process = process;
ActiveWindow = activeWindow;
}
 
/// <summary>
/// Selects the active window.
/// </summary>
public void Select()
{
if (SelectedWindow == null)
SelectedWindow = ActiveWindow;
}
 
/// <summary>
/// Selects the specified information.
/// </summary>
/// <param name="selectedWindow">The selected window.</param>
public void Select(WindowMonitor.WindowInformation selectedWindow)
{
if (SelectedWindow == null)
SelectedWindow = selectedWindow;
}
}
 
class WindowMonitor
{
#region NativeMethods
private static class NativeMethods
{
public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
 
struct Rect
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
 
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
 
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
 
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
 
[DllImport("user32", SetLastError = true)]
private static extern int GetWindowRect(IntPtr hWnd, ref Rect rect);
 
[DllImport("user32.dll")]
static extern bool EnumChildWindows(IntPtr hwndParent, Win32Callback lpEnumFunc, IntPtr lParam);
 
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
 
/// <summary>
/// Gets the foreground window.
/// </summary>
/// <value>
/// The foreground window.
/// </value>
public static IntPtr ForegroundWindow
{
get { return GetForegroundWindow(); }
}
 
/// <summary>
/// Gets the process associated with a window.
/// </summary>
/// <param name="hWnd">The window handle.</param>
/// <returns>The associated process.</returns>
public static Process GetWindowProcess(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero) return null;
uint pid;
GetWindowThreadProcessId(hWnd, out pid);
if (pid == 0)
{
ThrowWin32Error();
return null;
}
return Process.GetProcessById((int)pid);
}
 
/// <summary>
/// Gets the thread associated with a window.
/// </summary>
/// <param name="hWnd">The window handle.</param>
/// <returns>The associated process.</returns>
public static int GetWindowThread(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero) return 0;
uint pid;
var result = GetWindowThreadProcessId(hWnd, out pid);
if (pid == 0)
{
ThrowWin32Error();
return 0;
}
return result;
}
 
/// <summary>
/// Gets information about a window.
/// </summary>
/// <param name="hWnd">The window handle.</param>
/// <returns>The information about a window.</returns>
public static WindowInformation GetWindowInformation(IntPtr hWnd)
{
var sb = new StringBuilder(100);
var len = GetClassName(hWnd, sb, sb.Capacity);
 
return new WindowInformation(
handle: hWnd,
windowClass: sb.ToString().Substring(0, (int)len)
);
}
 
/// <summary>
/// Gets the rectangle of a window.
/// </summary>
/// <param name="hWnd">The window handle.</param>
/// <returns>The rectangle of the window.</returns>
public static Rectangle GetWindowRectangle(IntPtr hWnd)
{
var rect = new Rect();
GetWindowRect(hWnd, ref rect);
return new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
}
 
/// <summary>
/// Gets the child windows for the specified window.
/// </summary>
/// <param name="hWnd">The window handle.</param>
/// <returns>The list of child windows.</returns>
public static IEnumerable<IntPtr> GetChildWindows(IntPtr hWnd)
{
var result = new List<IntPtr>();
Win32Callback cb = (h, l) =>
{
result.Add(h);
return true;
};
EnumChildWindows(hWnd, cb, IntPtr.Zero);
return result;
}
 
public static int GetWindowLong(IntPtr hwnd, WindowLong longType)
{
return GetWindowLong(hwnd, (int)longType);
}
 
private static void ThrowWin32Error()
{
var err = Marshal.GetLastWin32Error();
ThrowWin32Error(err);
}
 
private static void ThrowWin32Error(int err)
{
if (err != 0) throw new Win32Exception(err);
}
}
#endregion
 
#region Enums
public enum WindowLong
{
ID = (-12),
Style = (-16),
ExtendedStyle = (-20)
}
 
[Flags]
public enum WindowStyles : long
{
Overlapped = 0,
Popup = 0x80000000,
Child = 0x40000000,
Minimize = 0x20000000,
Visible = 0x10000000,
Disabled = 0x8000000,
ClipSiblings = 0x4000000,
ClipChildren = 0x2000000,
Maximize = 0x1000000,
Caption = 0xC00000,
Border = 0x800000,
DialogFrame = 0x400000,
VerticalScroll = 0x200000,
HorizontalScroll = 0x100000,
SystemMenu = 0x80000,
ThickFrame = 0x40000,
Group = 0x20000,
TabStop = 0x10000,
MinimizeBox = 0x20000,
MaximizeBox = 0x10000,
}
#endregion
 
/// <summary>
/// Represents information about a window.
/// </summary>
public class WindowInformation
{
/// <summary>
/// Gets the handle of the window.
/// </summary>
/// <value>
/// The handle of the window.
/// </value>
public IntPtr Handle { get; private set; }
 
/// <summary>
/// Gets the window class.
/// </summary>
/// <value>
/// The window class.
/// </value>
public string WindowClass { get; private set; }
 
/// <summary>
/// Gets the child windows contained within this window.
/// </summary>
/// <value>
/// The child windows contained within this window.
/// </value>
public IEnumerable<WindowInformation> ChildWindows
{
get
{
foreach (var wnd in NativeMethods.GetChildWindows(Handle))
{
yield return NativeMethods.GetWindowInformation(wnd);
}
}
}
 
/// <summary>
/// Gets the style.
/// </summary>
/// <value>
/// The style.
/// </value>
public WindowStyles Style
{
get
{
return (WindowStyles)NativeMethods.GetWindowLong(Handle, WindowLong.Style);
}
}
 
/// <summary>
/// Initializes a new instance of the <see cref="WindowInformation" /> class.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="windowClass">The window class.</param>
public WindowInformation(IntPtr handle = default(IntPtr), string windowClass = null)
{
Handle = handle;
WindowClass = windowClass;
}
}
 
/// <summary>
/// Occurs when a valid window is activated.
/// </summary>
public event EventHandler<EventArgs> Activated;
 
/// <summary>
/// Occurs when the valid window's location changes.
/// </summary>
public event EventHandler<RectangleEventArgs> LocationChanged;
 
/// <summary>
/// Occurs when a valid window is deactivated.
/// </summary>
public event EventHandler<EventArgs> Deactivated;
 
/// <summary>
/// Occurs when a window needs to be selected.
/// </summary>
public event EventHandler<WindowSelectionEventArgs> SelectWindow;
 
private Process _targetProcess;
 
private System.Threading.Timer _checkProcessTimer;
private System.Threading.Timer _checkPositionTimer;
 
private Rectangle _lastRectangle;
 
/// <summary>
/// Initializes a new instance of the <see cref="WindowMonitor" /> class.
/// </summary>
/// <param name="processPredicate">The process predicate.</param>
/// <param name="windowPredicate">The window predicate.</param>
public WindowMonitor()
{
_checkProcessTimer = new System.Threading.Timer(CheckProcess, null, Timeout.Infinite, Timeout.Infinite);
_checkPositionTimer = new System.Threading.Timer(CheckPosition, null, Timeout.Infinite, Timeout.Infinite);
}
 
/// <summary>
/// Starts searching for the window.
/// </summary>
public void Start()
{
_checkProcessTimer = new System.Threading.Timer(CheckProcess, null, 0, Timeout.Infinite);
}
 
private void CheckProcess(object state)
{
Process process = null;
try
{
var foreground = NativeMethods.ForegroundWindow;
process = NativeMethods.GetWindowProcess(foreground);
var info = NativeMethods.GetWindowInformation(foreground);
 
var selectWindow = SelectWindow;
if (process != null && selectWindow != null)
{
var windowArgs = new WindowSelectionEventArgs(process, info);
selectWindow(this, windowArgs);
 
if (windowArgs.SelectedWindow != null)
{
process.Exited += process_Exited;
if (!process.HasExited)
{
_targetProcess = process;
_checkPositionTimer.Change(0, Timeout.Infinite);
 
var act = Activated;
if (act != null) act(this, EventArgs.Empty);
 
process = null; // Prevent dispose (see finally).
return;
}
}
}
 
var oldProcess = Interlocked.Exchange(ref _targetProcess, null);
if (oldProcess != null)
{
oldProcess.Exited -= process_Exited;
_checkPositionTimer.Change(Timeout.Infinite, Timeout.Infinite);
_checkProcessTimer.Change(0, Timeout.Infinite);
 
var deact = Deactivated;
if (deact != null) deact(this, EventArgs.Empty);
oldProcess.Dispose();
}
}
catch
{
// There are a whole class of UAC and race conditions that we would
// need to deal with, and would likely do the same thing I am doing
// right now for them.
}
finally
{
if (process != null)
{
process.Dispose();
}
}
 
_checkProcessTimer.Change(1000, Timeout.Infinite);
}
 
void process_Exited(object sender, EventArgs e)
{
var proc = Interlocked.Exchange(ref _targetProcess, null);
if (proc != null)
{
proc.Exited -= process_Exited;
_checkPositionTimer.Change(Timeout.Infinite, Timeout.Infinite);
_checkProcessTimer.Change(1000, Timeout.Infinite);
proc.Dispose();
}
}
 
private void CheckPosition(object state)
{
var proc = _targetProcess;
if (proc != null)
{
var foreground = NativeMethods.ForegroundWindow;
var windowArgs = new WindowSelectionEventArgs(proc, NativeMethods.GetWindowInformation(foreground));
var selectWindow = SelectWindow;
if (selectWindow != null) selectWindow(this, windowArgs);
 
if (windowArgs.SelectedWindow == null)
{
_checkProcessTimer.Change(0, Timeout.Infinite);
return;
}
 
Rectangle? rect = null;
try
{
rect = NativeMethods.GetWindowRectangle(windowArgs.SelectedWindow.Handle);
}
catch { }
 
if (rect != null)
{
if (rect.Value != _lastRectangle)
{
_lastRectangle = rect.Value;
var tmp = LocationChanged;
if (tmp != null) tmp(this, new RectangleEventArgs(rect.Value));
}
}
 
_checkPositionTimer.Change(100, Timeout.Infinite);
}
}
}
}

Added support for selecting the video area so that the overlay can easily be placed over it.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.