我试图让这件事整天工作。我试图将输入文本粘贴到另一个 Windows 应用程序中的文本框,(比如说 Chrome 的 URL 栏)我设法获得了主窗口 hwnd,但是当我使用 SendMessage 时,它只是改变了窗口的标题
所以我想弄清楚我究竟是如何动态地找出我的文本框的 hwnd 的。我也尝试过 Spy++,但由于某种原因,它为所有子窗口提供了相同的 hwnd,一定是做错了什么。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
private static IntPtr WinGetHandle(string wName)
{
IntPtr hWnd = IntPtr.Zero;
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(wName))
{
hWnd = pList.MainWindowHandle;
}
}
return hWnd;
}
static void Main(string[] args)
{
List<IntPtr> myList = GetChildWindows(WinGetHandle("chrome"));
foreach(IntPtr ptr in myList)
{
//No idea which one of those IntPtr is actually my textbox
//SendMessage((IntPtr)788018, 0x000C, 0, "text here");
}
Console.ReadLine();
}
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}
public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
}
}