遍历指定程序名窗口上的所有控件
Posted tiger9637
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遍历指定程序名窗口上的所有控件相关的知识,希望对你有一定的参考价值。
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]); } } }
以上是关于遍历指定程序名窗口上的所有控件的主要内容,如果未能解决你的问题,请参考以下文章