最近帮朋友做一个监控程序,需要知道当前系统的最前端进程。
搜了半天,一般出来的是下面这个。
[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;
}
}
}