首页 > 开发 > 综合 > 正文

在C#中使用SendMessage

2024-07-21 02:18:02
字体:
来源:转载
供稿:网友
国内最大的酷站演示中心!
在c#中使用sendmessage

--------------------------------------------------------------------------------

日期:2005-02-04
作者:floodzhu
备注:主要描述在调用api函数sendmessage时数据类型的转换。

--------------------------------------------------------------------------------

sendmessage是一个在user32.dll中声明的api函数,在c#中导入如下:

using system.runtime.interopservices;
[dllimport("user32.dll", entrypoint="sendmessagea")]
public static extern int sendmessage (intptr hwnd, int wmsg, intptr wparam, intptr lparam);
本文描述其参数 lparam 的用法,主要是数据类型之间的转化。

● 一种最简单的处理方式是声明多个sendmessage函数(overload),用所需的数据类型直接替换intptr。例如:

//声明:
[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);

rectangle rect = new rectangle();
sendmessage(this.richtextbox1.handle, em_getrect, (intptr)0, ref rect);
● 对要求返回字符串的类型(out string)可以用 stringbuilder 代替,此时不需要 out/ref。例如:

[dllimport("user32.dll", entrypoint="sendmessagea")]
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 的相关方法。例如:

[dllimport("user32.dll", entrypoint="sendmessagea")]
private static extern int sendmessage (intptr hwnd, int wmsg, intptr wparam, intptr lparam);

private void button2_click(object sender, system.eventargs e)
{
rectangle rect = new rectangle();
intptr buffer = marshal.allochglobal(marshal.sizeof(typeof(rectangle)));
marshal.structuretoptr(rect, buffer ,true);

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)
{
rectangle rect = new rectangle();
gchandle gch = gchandle.alloc(rect);

sendmessage(this.richtextbox1.handle, em_getrect, (intptr)0, (intptr)gch);
rect = (rectangle)marshal.ptrtostructure((intptr)gch, typeof(rectangle));

gch.free();
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表