首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 呼叫 Win32 API 函數:DllImport 屬性與 MessageBox 範例

     編輯:關於C語言

步驟

  1. 引入 using System.Runtime.InteropServices;
  2. 定義 static extern 方法,標註 [DllImport("dll名稱", EntryPoint="函數名", ...)]。
  3. 像呼叫一般方法一樣使用。

完整範例

using System;
using System.Runtime.InteropServices;

namespace NetMeeting.API
{
    public class Win32
    {
        [DllImport("user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
        public static extern int MessageBox(int hWnd, string text, string caption, uint type);
    }
}

// 呼叫端
using System;
using NetMeeting.API;

class Test
{
    public static void Main(string[] args)
    {
        Win32.MessageBox(0, "hello, this is a c# invoke win32 api", "test", 2);
    }
}

參數對應

  • hWnd:視窗控制代碼,0 表示無擁有者。
  • text:訊息內容。
  • caption:標題列文字。
  • type:按鈕/圖示組合(如 2 = Abort/Retry/Ignore + 警告圖示)。

進階主題

複雜結構體、回呼函數、字串編碼(CharSet)、SetLastError 等將於後續文章討論。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved