C# 对其他窗口发送文本
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace mysend
{
public partial class Form1 : Form
{
const int WM_SETTEXT = 0x0C;
IntPtr targethwnd;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(textBox2.Text.Length+1));
Marshal.Copy(textBox2.Text.ToCharArray(), 0, buffer, textBox2.Text.Length);
targethwnd = (IntPtr)Int32.Parse(textBox1.Text);
SendMessage(targethwnd , WM_SETTEXT, IntPtr.Zero, buffer);
Marshal.FreeHGlobal(buffer);
}
}
}
发送文本时SendMessage第四个字段是InPtr类型,要使用Marshal;
发送之后释放buffer,否则多几次就出问题;
目标句柄手动填入,发送到记事本;
更改计算器窗口的标题也是可以的;