程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 在C#中使用SendMessage

在C#中使用SendMessage

編輯:.NET實例教程

在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();
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved