1.撰写取得目前视窗的function
2.call function
撰写
using System.Runtime.InteropServices;//使用pinvoke (plateform invoke)的方式使用Win32 DLL时,必须使用System.Runtime.InteropServices这个namespace。//如果没有引用,会出现讯息:找不到型别或命名空间名称 'dllimport'
[DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();//取得目前视窗
先取得目前画面视窗,再取Process比对出ProcessName
private string getProcessNameFromFocusedWindow() { string ret = ""; System.Diagnostics.Process[] processCollection = System.Diagnostics.Process.GetProcesses(); if (processCollection != null && processCollection.Length >= 1 && processCollection[0] != null) { IntPtr activeWindowHandle = GetForegroundWindow(); foreach (System.Diagnostics.Process wordProcess in processCollection) { if (wordProcess.MainWindowHandle == activeWindowHandle) { return wordProcess.ProcessName; } } } return ret; }
//使用 getProcessNameFromFocusedWindow()
测试使用
1.新增aspx(也可以是AP的Form)
2.加入timer & call function getProcessNameFromFocusedWindow()用log记录
private System.Timers.Timer _TimersTimer; protected void Page_Load(object sender, EventArgs e) { this._TimersTimer = new System.Timers.Timer(); this._TimersTimer.Interval = 100; this._TimersTimer.Elapsed += new System.Timers.ElapsedEventHandler(_TimersTimer_Elapsed); this._TimersTimer.Start(); } void _TimersTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { string ret = getProcessNameFromFocusedWindow(); logP(ret); } //log private void logP(string str) { string filename = @"c:\log.log"; if (System.IO.File.Exists(filename) == false) { System.IO.FileStream fileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create); fileStream.Close(); //切记开了要关,不然会被佔用而无法修改喔!!! } using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename, true)) { file.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss:fff") + " " + str); } }
3.run程式 > 点Excel 点Word 点Outlook >关闭程式
4.查看Log,就会看到刚focus的视窗 Excel/Word/Outlook
user32真好用