此文记录的是一个关于关闭窗口工具类。
/*** 关闭窗口工具类 Austin Liu 刘恒辉 Project Manager and Software Designer E-Mail: lzhdim@163.com Blog: http://lzhdim.cnblogs.com Date: 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); } }
Austin Liu 刘恒辉
Project Manager and Software Designer E-Mail:lzhdim@163.com Blog:https://lzhdim.cnblogs.com 欢迎收藏和转载此博客中的博文,但是请注明出处,给笔者一个与大家交流的空间。谢谢大家。 |