管理

关闭窗口工具类 - C#小函数类推荐

Posted on 2024-08-01 09:30  lzhdim  阅读(10424)  评论(0编辑  收藏  举报

       此文记录的是一个关于关闭窗口工具类。

/***

    关闭窗口工具类

    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);
    }
}

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved