C# 向不同文本框发送不同内容的教程
要向不同的文本框发送不同的内容,你可以使用 'SendMessage' 函数来模拟向窗口发送消息。
首先,你需要获取每个文本框的句柄(handle),可以使用 'FindWindowEx' 函数来查找指定窗口的子窗口。
然后,使用 'SendMessage' 函数发送 'WM_SETTEXT' 消息给目标文本框,以设置其文本内容。
下面是一个示例代码,演示如何向不同的文本框发送不同的内容:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
// 导入 Windows API 函数
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindowEx(IntPtr hWndParent, IntPtr hWndChildAfter, string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, string lParam);
// 常量定义
private const int WM_SETTEXT = 0x000C;
static void Main(string[] args)
{
// 获取父窗口的句柄
IntPtr parentWindowHandle = FindWindow(null, "父窗口标题"); // 替换为父窗口的标题
if (parentWindowHandle != IntPtr.Zero)
{
// 获取子窗口的句柄
IntPtr textBox1Handle = FindWindowEx(parentWindowHandle, IntPtr.Zero, "Edit", null); // 替换为文本框1的类名
IntPtr textBox2Handle = FindWindowEx(parentWindowHandle, IntPtr.Zero, "Edit", null); // 替换为文本框2的类名
if (textBox1Handle != IntPtr.Zero && textBox2Handle != IntPtr.Zero)
{
// 向文本框1发送文本
SendMessage(textBox1Handle, WM_SETTEXT, 0, "文本框1的内容");
// 向文本框2发送文本
SendMessage(textBox2Handle, WM_SETTEXT, 0, "文本框2的内容");
}
else
{
Console.WriteLine("未找到子窗口!");
}
}
else
{
Console.WriteLine("未找到父窗口!");
}
}
}
在示例代码中,我们使用 'FindWindow' 函数获取父窗口的句柄。然后,通过调用 'FindWindowEx' 函数,我们分别获取了两个文本框的句柄。接下来,使用 'SendMessage' 函数,我们向每个文本框发送了 'WM_SETTEXT' 消息,以设置它们的文本内容。
请将示例代码中的 "父窗口标题" 替换为你要找到的父窗口的实际标题。同时,将 "文本框1的内容" 和 "文本框2的内容" 替换为你要发送到对应文本框的实际内容。确保你的应用程序具有足够的权限来操作目标窗口和文本框。
原文地址: https://www.cveoy.top/t/topic/PTv 著作权归作者所有。请勿转载和采集!