[转]谁抢了我的焦点

原文链接 http://blog.csdn.net/sytzz/article/details/25372103

当前激活的窗口总是每隔几秒失去焦点,过0.5~1秒焦点回来,导致输入无法正常工作,严重影响使用心情和效率。

窗口失去焦点,无非就是别的窗口将焦点抢占过去,如果能找到是什么程序抢占了窗口焦点,禁用之就可以解决。

因为是解决Windows问题,使用微软自家的C#解决问题。

打开VS创建C# Windows应用程序工程,使用一个Lable显示信息,一个Timer定时获取当前激活窗口(毫秒级),并且将信息显示到Lable即可。当前台窗口焦点改变,从Lable中可以看到当前前台程序。

附上监控程序部分逻辑代码(未使用任何编码规范,未加任何注释),窗口代码使用窗口设计器生成即可。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;using System.Text;using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetForegroundWindow();//获取当前激活窗口

        [DllImport("user32", SetLastError = true)]
        public static extern int GetWindowText(
        IntPtr hWnd, //窗口句柄
        StringBuilder lpString, //标题
        int nMaxCount  //最大值
        );

        [DllImport("user32.dll")]
        private static extern int GetClassName(
            IntPtr hWnd, //句柄
            StringBuilder lpString, //类名
            int nMaxCount //最大值
        );

        public Form1()
        {
            InitializeComponent();

            timer1.Start();
        }
private void timer1_Tick(object sender, EventArgs e)
        {
            IntPtr myPtr = GetForegroundWindow();

            // 窗口标题
            StringBuilder title = new StringBuilder(255);
            GetWindowText(myPtr, title, title.Capacity);

            // 窗口类名
            StringBuilder className = new StringBuilder(256);
            GetClassName(myPtr, className, className.Capacity);

            label1.Text = myPtr.ToString() + "
" + title.ToString() + "
" + className.ToString();
        }
    }
}

发现抢你焦点的程序了没,关掉它吧。

原文地址:https://www.cnblogs.com/z5337/p/4431680.html