國內(nèi)最大的酷站演示中心!
在c#中使用sendmessage
--------------------------------------------------------------------------------
日期:2005-02-04
作者:floodzhu
備注:主要描述在調(diào)用api函數(shù)sendmessage時(shí)數(shù)據(jù)類型的轉(zhuǎn)換。
--------------------------------------------------------------------------------
sendmessage是一個(gè)在user32.dll中聲明的api函數(shù),在c#中導(dǎo)入如下:
using system.runtime.interopservices;
[dllimport("user32.dll", entrypoint="sendmessagea")]
public static extern int sendmessage (intptr hwnd, int wmsg, intptr wparam, intptr lparam);
本文描述其參數(shù) lparam 的用法,主要是數(shù)據(jù)類型之間的轉(zhuǎn)化。
● 一種最簡單的處理方式是聲明多個(gè)sendmessage函數(shù)(overload),用所需的數(shù)據(jù)類型直接替換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);
//調(diào)用:
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);
● 對(duì)要求返回字符串的類型(out string)可以用 stringbuilder 代替,此時(shí)不需要 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 類型統(tǒng)一處理的話,可以借助于 marshal 或者 gchandle 的相關(guān)方法。例如:
[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();
}