在C#中调用Windows API (转)

    C#代码处于托管状态下工作,所以有完善的内存回收管理、类型安全性。但有时候,你想应用你以前在VC/Delphi下编写的非托管代码,C#同样也提供了这种Windows API调用支持,比如System.Win32名字空间下就是通过调用操作系统原有API的,以下我以“在VC中使用Delphi构造公共对话框”中的一个密码认证对话框的调用为例,说明如果在C#中调用系统标准的API函数。
    首先我们来看CommonDlg.dll的API接口声明:
function ShowLoginDlg(hHandle: HWND;
         szUser: PChar;
         szPassword: PChar
         ): Integer; stdcall;
    要在C#中调用这个API,必须先声明该非托管API的接口:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace FormTest
{
    
/// <summary>
    
/// CommonDlgAPI 的摘要说明。
    
/// </summary>

    public class CommonDlgAPI
    
{
        
public CommonDlgAPI()
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
        }

        
        [DllImport(
"CommonDlg.dll", CharSet = CharSet.Ansi)]
        
public static extern int ShowLoginDlg(int hHandle, StringBuilder szUser, StringBuilder szPassword);
    }

}
    然后用如下的C#代码来调用该接口:
        private void buttonLogin_Click(object sender, System.EventArgs e)
        
{
            StringBuilder szUser 
= new StringBuilder(32);
            StringBuilder szPasswd 
= new StringBuilder(32);

            
if (CommonDlgAPI.ShowLoginDlg(0, szUser, szPasswd) == 1)
            
{
                MessageBox.Show(szUser.ToString() 
+ "/" + szPasswd.ToString());
            }

        }

    显然,[DllImport("CommonDlg.dll", CharSet = CharSet.Ansi)]是整个声明的关键,这里声明一个导入API所在动态库的文件名为CommonDlg.dll,参数传递为ANSI类似的,如果的Unicode类形的API,则设置为CharSet.Unicode。

继续中……
        1) 各种VC/Delphi参数类型到C#托管类型的映射关系;
        2) 技术实现内幕;
        ……
原文地址:https://www.cnblogs.com/ZhouXiHong/p/481987.html