iT邦幫忙

3

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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言