[C#] 取得目前视窗程式(user32)

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真好用


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章