找到当前Windows显示的最前端的窗体程序

最近帮朋友做一个监控程序,需要知道当前系统的最前端进程。
搜了半天,一般出来的是下面这个。

    [DllImport("User32", CharSet = CharSet.Ansi, SetLastError = true)]
        private extern static int GetWindowLong(
                                System.IntPtr hWnd,
                                System.Int32 nIndex

        );

        private bool isWndTopMost(IntPtr hwnd)
        {
            if ((GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) > 0)
                return true;
            else
                return false;
        }

这段代码的意思就是判断是否有TopMost属性,也就是是否设置置顶属性。
一般上所有程序都可以设置TopMost属性,如果你是最后一个设置的,那很好,Windows显示的最前端的程序就你刚才设置的那个。如果不是,就不会是你想要的那个程序窗口。

事实上我想知道的是当前Windows显示的最前端的窗体程序,其实很简单,下面的函数就可以了。

IntPtr GetForegroundWindow();

具体的例子如下(C#实现), 通过定时器获取当前的最前端窗体的句柄,然后通过Process找到进程信息。

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        private void timer1_Tick(object sender, EventArgs e)
        {
            System.IntPtr topMostProcess = GetForegroundWindow();
            Process[] ps = Process.GetProcesses();
            foreach (Process app in ps)
            {
                IntPtr hWnd = app.MainWindowHandle;
                if (hWnd == topMostProcess)
                {
                    richTextBox1.AppendText("\r\n" + app.MainModule.FileName);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值