1. 程式人生 > >遍歷指定程序名窗口上的所有控件

遍歷指定程序名窗口上的所有控件

inter equal getclass app first acc sum user dllimport

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;
using System.Diagnostics;

namespace WindowsFormsApp1
{
    public partial class
Form1 : Form { [DllImport("user32.dll", EntryPoint = "FindWindowExA")] private static extern IntPtr FindWindowExA(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("user32.dll")] private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int
nMacCount); [DllImport("user32.dll")] private static extern int GetWindowTextA(IntPtr hWnd, StringBuilder lpString, int nMaxCount); public Form1() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="ParPtr">
Set with main window handle on first call</param> /// <param name="ChildAfterPtr"></param> /// <param name="CurNode"></param> /// <returns></returns> private IntPtr GetChild(IntPtr ParPtr, IntPtr ChildAfterPtr, TreeNode CurNode) { // IntPtr ChildPtr = IntPtr.Zero; IntPtr NextChildPtr = IntPtr.Zero; IntPtr ChildPtr = FindWindowExA(ParPtr, ChildAfterPtr, null, null); StringBuilder CurClassName = new StringBuilder(); StringBuilder CurWindowTitle = new StringBuilder(); if (ChildPtr != IntPtr.Zero) { GetClassName(ChildPtr, CurClassName, 100); GetWindowTextA(ChildPtr, CurWindowTitle, 100); CurNode.Nodes.Add(ChildPtr.ToString("X2") + " : " + CurClassName.ToString() + " : " + CurWindowTitle); NextChildPtr = GetChild(ChildPtr, IntPtr.Zero, CurNode.Nodes[CurNode.Nodes.Count - 1]); // for next level controls } if (ChildPtr != IntPtr.Zero) { NextChildPtr = GetChild(ParPtr, ChildPtr, CurNode); // for same level controls } return ChildPtr; } private void button1_Click(object sender, EventArgs e) { string MainWindowsProcName = textBox1.Text; IntPtr HeMainWindowHandle = IntPtr.Zero; StringBuilder CurClassName = new StringBuilder(); StringBuilder CurWindowTitle = new StringBuilder(); treeView1.Nodes.Clear(); Process[] AllHeProcs = Process.GetProcessesByName(MainWindowsProcName); // get process by specific name if (AllHeProcs.Count() != 1) { MessageBox.Show("Process instance count not equal 1, use first one"); } HeMainWindowHandle = AllHeProcs[0].MainWindowHandle; // get main window handle GetClassName(HeMainWindowHandle, CurClassName, 100); GetWindowTextA(HeMainWindowHandle, CurWindowTitle, 100); treeView1.Nodes.Add(HeMainWindowHandle.ToString("X2") + " : " + CurClassName + " : " + CurWindowTitle); GetChild(HeMainWindowHandle, IntPtr.Zero, treeView1.Nodes[0]); } } }

技術分享圖片

遍歷指定程序名窗口上的所有控件