【轉】在C#中使用SendMessage

來源:互聯網
上載者:User

標籤:

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

【轉】在C#中使用SendMessage

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.