Click here to Skip to main content
15,883,705 members
Articles / Desktop Programming / WPF

Catel - Part 4 of n: Unit testing with Catel

Rate me:
Please Sign up or sign in to vote.
4.55/5 (10 votes)
28 Jan 2011CPOL11 min read 48.9K   572   11  
This article explains how to write unit tests for MVVM using Catel.
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FrameworkElementExtensions.cs" company="Catel development team">
//   Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
//   Extensions for <see cref="System.Windows.FrameworkElement" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using log4net;

namespace Catel.Windows
{
	/// <summary>
	/// Extensions for <see cref="System.Windows.FrameworkElement"/>.
	/// </summary>
	public static class FrameworkElementExtensions
	{
		#region Win32
		[DllImport("user32.dll", SetLastError = true)]
		static extern bool BringWindowToTop(IntPtr hWnd);

		[DllImport("user32.dll", SetLastError = true)]
		static extern bool BringWindowToTop(HandleRef hWnd);

		[DllImport("user32.dll", SetLastError = true)]
		static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

		[DllImport("user32.dll")]
		static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

		/// <summary>
		/// The GetForegroundWindow function returns a handle to the foreground window.
		/// </summary>
		[DllImport("user32.dll")]
		static extern IntPtr GetForegroundWindow();

		[DllImport("kernel32.dll")]
		static extern IntPtr GetCurrentThreadId();

		[DllImport("user32.dll", SetLastError = true)]
		static extern bool AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, bool fAttach);

		[DllImport("user32.dll")]
		static extern IntPtr GetLastActivePopup(IntPtr hWnd);

		[DllImport("user32.dll")]
		static extern IntPtr SetActiveWindow(IntPtr hWnd);
		#endregion

		#region Variables
        /// <summary>
        /// The <see cref="ILog">log</see> object.
        /// </summary>
		private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion

		#region Methods
		/// <summary>
		/// Activates the window this framework element contains to.
		/// </summary>
		/// <param name="frameworkElement">Reference to the current <see cref="FrameworkElement"/>.</param>
		public static void BringWindowToTop(this FrameworkElement frameworkElement)
		{
			if (frameworkElement == null)
			{
			    return;
			}

			// Check if the framework element has an owner
			Window ownerWindow = null;
			FrameworkElement parentFrameworkElement = frameworkElement;
			while (parentFrameworkElement != null)
			{
				if (parentFrameworkElement is Window)
				{
					ownerWindow = (Window)parentFrameworkElement;
					break;
				}

				parentFrameworkElement = parentFrameworkElement.Parent as FrameworkElement;
			}

			try
			{
				// Get the handle (of the window or process)
				IntPtr windowHandle = (ownerWindow != null) ? new WindowInteropHelper(ownerWindow).Handle :
					Process.GetCurrentProcess().MainWindowHandle;
				if (windowHandle != IntPtr.Zero)
				{
					SetForegroundWindowEx(windowHandle);
				}
			}
			catch (Exception)
			{
			}
		}

		/// <summary>
		/// Get first parent binding group from specified element.
		/// </summary>
		/// <param name="frameworkElement">Reference to the current <see cref="FrameworkElement"/>.</param>
		/// <returns>The first parent BindingGroup or null when not exists.</returns>
		public static System.Windows.Data.BindingGroup GetParentBindingGroup(this FrameworkElement frameworkElement)
		{
			if (frameworkElement == null)
			{
			    return null;
			}

			if (frameworkElement.BindingGroup != null)
			{
			    return frameworkElement.BindingGroup;
			}

			return GetParentBindingGroup(LogicalTreeHelper.GetParent(frameworkElement) as FrameworkElement);
		}

		/// <summary>
		/// Sets the foreground window (some "dirty" win32 stuff).
		/// </summary>
		/// <param name="hWnd">Handle of the window to set to the front.</param>
		/// <remarks>
		/// This method takes over the input thread for the window. This means that you are unable
		/// to debug the code between "Attach" and "Detach" since the input thread of Visual Studio
		/// will be attached to the thread of the application.
		/// </remarks>
		private static void SetForegroundWindowEx(IntPtr hWnd)
		{
			IntPtr foregroundWindowThreadID = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
			IntPtr currentThreadID = GetCurrentThreadId();

			if (!AttachThreadInput(foregroundWindowThreadID, currentThreadID, true))
			{
				Log.Warn(Properties.TraceMessages.AttachThreadInputFailed, Marshal.GetLastWin32Error());
				return;
			}

			IntPtr lastActivePopupWindow = GetLastActivePopup(hWnd);
			SetActiveWindow(lastActivePopupWindow);

			if (!AttachThreadInput(foregroundWindowThreadID, currentThreadID, false))
			{
				Log.Warn(Properties.TraceMessages.DetachThreadInputFailed);
				return;
			}

			BringWindowToTop(hWnd);
		}
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions