在我的c#应用程序中,我想要窗体的窗口句柄。我知道" .exe"窗口的名称,所以我试过" GetProcessesByName"功能。我得到了应用程序的句柄,但不知道如何获取它的子窗口。指导我
Process[] p = System.Diagnostics.Process.GetProcessesByName("MyProcess");
foreach (Process p1 in p)
{
MessageBox.Show(GetWindowText(p1.MainWindowHandle));
}
使用句柄p1
,我需要获取p1
的子窗口句柄。怎么做?
答案 0 :(得分:0)
我使用“ GetProcessesByName ”等功能来获取主窗口的句柄和“ EnumChildWindows ”以获取子窗口的句柄。对于源代码,
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.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using Microsoft.Win32;
[DllImport("user32.Dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam);
Process[] p = System.Diagnostics.Process.GetProcessesByName("StikyNot"); //this is for sticky notes
foreach (Process p1 in p)
{
IntPtr MainWindowHandle = p1.MainWindowHandle;
List<IntPtr> GetChildWindowsHandle=GetChildWindows(MainWindowHandle);
}
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
Win32Callback childProc = new Win32Callback(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}