iT邦幫忙

1

[C#] 取得目前視窗title(user32)

  • 分享至 

  • xImage
  •  

1.撰寫取得目前視窗title
先取目前畫面,再用目前畫面去取title
2.測試

    using System.Runtime.InteropServices;
    [DllImport("User32.dll")]
    private static extern IntPtr GetForegroundWindow();//取得目前畫面視窗

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd,System.Text. StringBuilder text, int count);//取視窗title

先取目前畫面視窗,再用視窗去取title

        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            System.Text.StringBuilder Buff = new System.Text.StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

測試
1.加入timer & 記錄focus widow Title
2.run
3.點視窗A,點視窗B,點視窗C,關閉程式
4.查看log,是否記錄視窗A,點視窗B,點視窗C的title


        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 = GetActiveWindowTitle();
            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);
            }
        } 

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

尚未有邦友留言

立即登入留言