C# API sendmessage()函数 部分讲解
2021-03-05 19:26
标签:extern details show 处理 str 简单 cli detail end 在C#中使用SendMessage using System.Runtime.InteropServices; ● 一种最简单的处理方式是声明多个SendMessage函数(overload),用所需的数据类型直接替换IntPtr。例如: //声明: Rectangle rect = new Rectangle(); [DllImport("user32.dll", EntryPoint="SendMessageA")] [DllImport("user32.dll", EntryPoint="SendMessageA")] private void button2_Click(object sender, System.EventArgs e) SendMessage(this.richTextBox1.Handle, EM_GETRECT, (IntPtr)0, buffer); rect = (Rectangle)Marshal.PtrToStructure(buffer, typeof(Rectangle)); Marshal.FreeHGlobal(buffer); private void button2_Click(object sender, System.EventArgs e) SendMessage(this.richTextBox1.Handle, EM_GETRECT, (IntPtr)0, (IntPtr)gch); gch.Free(); C# API sendmessage()函数 部分讲解 标签:extern details show 处理 str 简单 cli detail end 原文地址:https://www.cnblogs.com/2SBC/p/12892647.html
日期:2005-02-04
作者:floodzhu
备注:主要描述在调用API函数SendMessage时数据类型的转换。
SendMessage是一个在user32.dll中声明的API函数,在C#中导入如下:
[DllImport("user32.dll", EntryPoint="SendMessageA")]
public static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
本文描述其参数 lParam 的用法,主要是数据类型之间的转化。
[DllImport("user32.dll", EntryPoint="SendMessageA")]
private static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);
[DllImport("user32.dll", EntryPoint="SendMessageA")]
private static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam, ref Rectangle lParam);
//调用:
string s = "hello, floodzhu";
SendMessage(this.textBox1.Handle, WM_SETTEXT, IntPtr.Zero, s);
SendMessage(this.richTextBox1.Handle, EM_GETRECT, (IntPtr)0, ref rect);
● 对要求返回字符串的类型(out string)可以用 StringBuilder 代替,此时不需要 out/ref。例如:
private static extern int SendMessage (IntPtr hwnd, int wMsg, int wParam, StringBuilder lParam);
private void button1_Click(object sender, System.EventArgs e)
{
const int buffer_size = 1024;
StringBuilder buffer = new StringBuilder(buffer_size);
SendMessage(this.textBox1.Handle, WM_GETTEXT, buffer_size, buffer);
//MessageBox.Show(buffer.ToString());
}
● 如果想用 InPtr 类型统一处理的话,可以借助于 Marshal 或者 GCHandle 的相关方法。例如:
private static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
{
Rectangle rect = new Rectangle();
IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Rectangle)));
Marshal.StructureToPtr(rect, buffer ,true);
}
或者
{
Rectangle rect = new Rectangle();
GCHandle gch = GCHandle.Alloc(rect);
rect = (Rectangle)Marshal.PtrToStructure((IntPtr)gch, typeof(Rectangle));
}
————————————————
版权声明:本文为CSDN博主「floodzhu」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/floodzhu/article/details/280817