此文记录的是一个关于关闭窗口工具类。
/***关闭窗口工具类Austin Liu 刘恒辉Project Manager and Software DesignerE-Mail: lzhdim@163.comBlog: http://lzhdim.cnblogs.comDate: 2024-01-15 15:18:00使用方法:CloseWindowUtil.CloseWindow(this.Handle);***/namespace Lzhdim.LPF.Utility
{using System;using System.Diagnostics;using System.Reflection;using System.Runtime.InteropServices;/// <summary>/// 关闭窗口工具类/// </summary>public class CloseWindowUtil{/// <summary>/// 定义关闭窗口的消息常量/// </summary>private const uint WM_CLOSE = 0x0010;/// <summary>/// 关闭主窗体,相当于退出当前应用/// </summary>public static void CloseMainWindow(){Process currentProcess = Process.GetCurrentProcess();foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)){if (Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == process.MainModule.FileName){if (process.MainWindowHandle != IntPtr.Zero){PostMessage(process.MainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);}break;}}}/// <summary>/// 关闭窗体/// </summary>/// <param name="hWnd">窗体句柄</param>public static void CloseWindow(IntPtr hWnd){PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);}[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);}
}