Closing parent from Child Window WPF C#

Closing parent from Child Window WPF C#

WPF

Windows Presentation Foundation (WPF) is an open-source graphical subsystem (similar to WinForms) originally developed by Microsoft for rendering user interfaces in Windows-based applications. Today we will discuss another complex scenario where your entire application is running based on Threads like EXCEL COM.

Problem Statement

Main window is running on a thread and on click of some button on the main window a child window gets opened and of course it is also launched using a thread. Now real problem, you cannot kill main window until you terminate the child window thread. If you try to close main window closing, closed or any other event of Child Window you have to face “The process cannot access the file because it is being used by another process” Error.

Resolution

Ultimately, I tried lots of ways to terminate the main window thread from child window but no luck. And I have to go straight with scripting approach using Win APIs. So here is the solution step by step:

  • Need API which will identify your window by its title and returns handle for it
  • Need API which terminates your main window

Code example

using System.Runtime.InteropServices;

public class WindowsApi
{
	public static IntPtr parentHandle = IntPtr.Zero;

	[DllImport("user32.dll", CharSet = CharSet.Auto)]
	private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

	private const UInt32 WM_CLOSE = 0x0010;
	[DllImport("user32.dll")]
	private static extern IntPtr GetForegroundWindow();

	public static IntPtr GetForegrouondWindow(string winTitle)
	{
		IntPtr parentHandle =IntPtr.Zero;
		foreach (System.Diagnostics.Process pList in System.Diagnostics.Process.GetProcesses())
		{
			if (pList.MainWindowTitle == winTitle)
			{
				parentHandle = pList.MainWindowHandle;
				break;
			}
		}
		return parentHandle;
	}
	public static void CloseWindow(IntPtr hwnd)
	{
		SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
	}
}

The very first call you need to make is for GetForegrouondWindow by passing the title of your main window that you wish to close upon closing child window. Hold the Handler value in a variable and pass it to CloseWindow at the time of Terminating Thread on child window.

Next>>Determining Shapes in Excel Worksheet C#

Leave a Reply

Your email address will not be published.