網頁

2011年7月6日 星期三

[C#] WindowFromPoint 偵側視窗名稱

[C#] 偵側桌面上程式視窗名稱 (仿 Spy++ )

WindowFromPoint Function

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices; //For DllImport

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // WF_GetFormInformation 會用到的 WinAPI
        [DllImport("user32.dll")]
        public static extern IntPtr WindowFromPoint(Point Point);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int GetWindowTextLength(IntPtr hWnd);
        private void button1_Click(object sender, EventArgs e)
        {

            // 關鍵: 先隱藏本表單以利偵側本 Winform 下的程式
            this.Hide();

            // 透過 WindowFromPoint 方法來取得當下座標程式的 IntPtr (句柄)
            Point ptCursor = new Point();
            IntPtr hWnd = WindowFromPoint(ptCursor); 
            // 取得視窗名稱長度
            int length = GetWindowTextLength(hWnd) + 1;
            StringBuilder sb = new StringBuilder(length);
            // 取得視窗名稱
            int i = GetWindowText(hWnd, sb, length);
            label1.Text = ""; //清空舊資訊
            label1.Text = sb.ToString(); 

            // 最後再把原本的 Winform Show 出來~
            this.Show();
        }
    }
}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。