当前位置:   article > 正文

C# 对其他窗口发送文本

C# 对其他窗口发送文本
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Runtime.InteropServices;
  11. namespace mysend
  12. {
  13. public partial class Form1 : Form
  14. {
  15. const int WM_SETTEXT = 0x0C;
  16. IntPtr targethwnd;
  17. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  18. public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. }
  23. private void button1_Click(object sender, EventArgs e)
  24. {
  25. IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(textBox2.Text.Length+1));
  26. Marshal.Copy(textBox2.Text.ToCharArray(), 0, buffer, textBox2.Text.Length);
  27. targethwnd = (IntPtr)Int32.Parse(textBox1.Text);
  28. SendMessage(targethwnd , WM_SETTEXT, IntPtr.Zero, buffer);
  29. Marshal.FreeHGlobal(buffer);
  30. }
  31. }
  32. }

发送文本时SendMessage第四个字段是InPtr类型,要使用Marshal;

发送之后释放buffer,否则多几次就出问题;

目标句柄手动填入,发送到记事本;

更改计算器窗口的标题也是可以的;

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45170
推荐阅读
相关标签
  

闽ICP备14008679号