c# 使form窗体在系统中获得焦点

发布时间 2023-09-13 08:59:21作者: 青丝·旅人

使用命名空间System.Runtime.InteropServices

using System.Runtime.InteropServices;

 

调用API方法

        /// <summary>
        /// 获得当前活动窗体的句柄
        /// </summary>
        /// <returns>返回窗体句柄</returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetForegroundWindow();

        /// <summary>
        /// 设置此窗体句柄的窗体为活动窗体
        /// </summary>
        /// <param name="hWnd">指定窗口句柄</param>
        /// <returns>返回设置结果</returns>
        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

 

设置

                if (!Focused)
                {
                    GetForegroundWindow();// 此函数返回一个当前活动窗体的句柄
                    SetForegroundWindow(this.Handle);// 设置自己为活动窗体
                    Focus();//软件获取焦点
                }