[C#]透過 SHDocVw 與 GetForegroundWindow 取得正在使用的 Internet Explorer 網址

  • 32278
  • 0
  • 2010-08-03

[C#]透過 SHDocVw 與 GetForegroundWindow 取得正在使用的 Internet Explorer 網址

 

1. 問題描述

如何取得正在使用的 Interner Explorer 網址

 

2. 方法

(1) 取得 Internet Explorer 網址

先加入參考 Microsoft HTML Object Library 與 Microsoft Internet Controls

接著請參考以下程式碼與註解


            this.lbURL.Items.Clear();

            // 取得目前 Shell 的所有視窗
            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            foreach (SHDocVw.InternetExplorer ie in shellWindows)
            {
                // 判斷視窗是否為 iexplore
                if (Path.GetFileNameWithoutExtension(ie.FullName).ToLower().Equals("iexplore"))
                {
                    this.lbURL.Items.Add(ie.LocationURL);
                }
            }

 

image

 

(2) 透過 Windows API GetForegroundWindow 取得正在使用視窗[前景]的控制代碼

將宣告 GetForegroundWindow 部分加入,並且在取得 Internet Explorer 視窗時,判斷是否為正在使用前景視窗


       // 
        // Windows API : GetForegroundWindow
        // 取得正在使用視窗[前景]的控制代碼
        // 
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.lbURL.Items.Clear();

            // 取得目前 Shell 的所有視窗
            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            foreach (SHDocVw.InternetExplorer ie in shellWindows)
            {
                // 判斷視窗是否為 iexplore
                if (Path.GetFileNameWithoutExtension(ie.FullName).ToLower().Equals("iexplore"))
                {
                    // 判斷此 Internet Explorer 是否為正在使用視窗[前景]
                    if (ie.HWND == GetForegroundWindow().ToInt32())
                    {
                        this.txtURL.Text = ie.LocationURL;
                    }

                    this.lbURL.Items.Add(ie.LocationURL);
                }
            }
        }

 

image

 

3. 相關連結

加入參考的DLL檔後出現錯誤?

如何自動找到正確的IE視窗並自動登入Gmail or Yahoo Mail