2012-05-19

Articles

WindowObserver

 

If you need the WinAPI events like the resize, click in the title bar or moving the window you can use this observer object. Just let observe a window and catch the incoming events.

 

alt

 

Usage

<Window x:Class="DW.SharpTools.Demo.ObservedWindow"
		xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
		xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		WindowStartupLocation="CenterScreen"
		Title="Observed Window"
		Height="300"
		Width="300">
	<DockPanel>
		<TextBlock Text="Move or resize the window"
				   HorizontalAlignment="Center"
				   DockPanel.Dock="Top" />
		<ListBox ItemsSource="{Binding Items}" />
	</DockPanel>
</Window>
using System.Collections.ObjectModel;
using System.Windows;

namespace DW.SharpTools.Demo
{
	public partial class ObservedWindow : Window
	{
		private readonly WindowObserver _windowObserver;

		public ObservableCollection<string> Items { get; set; }

		private int _moveCount = 1;
		private int _sizeCount = 1;

		public ObservedWindow()
		{
			InitializeComponent();
			DataContext = this;

			Items = new ObservableCollection<string>();

			_windowObserver = new WindowObserver(this);
			_windowObserver.AddCallback(NotifyMessage);
		}

		private void NotifyMessage(NotifyEventArgs e)
		{
			if (e.MessageId == WindowMessages.WM_MOVING)
				Items.Insert(0, string.Format("{0} WM_MOVING", _moveCount++));
			else if (e.MessageId == WindowMessages.WM_SIZING)
				Items.Insert(0, string.Format("{0} WM_SIZING", _sizeCount++));
		}

		/*
		 * Alternative usages:
		 * 
		 * 1. The "Message" event
		 *     _windowObserver.Message += ...
		 *     
		 * 2. Add callbacks just for specific messages
		 *     _windowObserver.AddCallbackFor(WindowMessages.WM_MOVING, NotifyMovingMessage);
		 * */
	}
}