c# 强制wpf窗体最前

1:引用4个API函数

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();


        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);


        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);


        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd,int hWndInsertAfter,int X,int Y,int         cx,int cy,int uFlags );       

        

         [DllImport("user32.dll")]
        public static extern bool IsWindowVisible(IntPtr hWnd);

2:在窗体的LOAD事件中添加取消令牌

 CancellationTokenSource cancellationTokenSource; //声明字段


 //LOAD事件中添加
 cancellationTokenSource = new CancellationTokenSource();//添加取消令牌
 ShowWindowAsync();//开始程序运行

3:添加方法设置窗体参数

      public static void SetWindowPos(IntPtr hWnd)
        {
            //0x0010为不激活窗口,这个比较关键
            SetWindowPos(hWnd, -1, 0, 0, 0, 0, 0x001 | 0x002 | 0x0010 | 0x040);
        }

4:创建方法开始运行程序强制窗体靠前

        private void ShowWindowAsync()
        {
            Task task = new Task(() =>
            {
                IntPtr hWnd = GetForegroundWindow();
                while (!cancellationTokenSource.IsCancellationRequested)
                {
                    if (hWnd != IntPtr.Zero || GetForegroundWindow() != hWnd)
                    {
                        //选中当前的句柄窗口
                        SetWindowPos(hWnd);
                        //SendKeys.SendWait(" ");
                    }
                }
            });
            task.Start();
        }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值