.net 下对winapi的调用

C#例子

using   System.Runtime.InteropServices;    

[DllImport("user32.dll")]     
  public   static   extern   int   SendMessage(IntPtr   hWnd,int   Msg,int   wParam,int   lParam);     
    
  //此处主要用来让窗口置于最前(SetWindowPos(this.Handle,-1,0,0,0,0,0x4000|0x0001|0x0002);)     
  [System.Runtime.InteropServices.DllImport("user32.dll")]     
  public   static   extern   bool   SetWindowPos(IntPtr   hWnd,     
   int   hWndInsertAfter,     
   int   X,     
   int   Y,     
   int   cx,     
   int   cy,     
   int   uFlags     
   );      

在C#里调用Win32函数有这么几个要点。

第一:名字要与Win32 API的完全一样。

第二:函数除了要有相应的DllImport类修饰外,还要声明成public static extern类型的。

第三:函数的返回值和参数类型要与Win32 API完全一致!

窗口指针 hWnd 可以用 int 也可以用 IntPtr   推荐使用 IntPtr  

附1 常用Win32数据类型与.NET平台数据类型的对应表

Figure 2 Non-Pointer Data Types

Win32 TypesSpecificationCLR Type
char, INT8, SBYTE, CHAR 8-bit signed integer System.SByte
short, short int, INT16, SHORT 16-bit signed integer System.Int16
int, long, long int, INT32, LONG32, BOOL, INT 32-bit signed integer System.Int32
__int64, INT64, LONGLONG 64-bit signed integer System.Int64
unsigned char, UINT8, UCHAR, BYTE 8-bit unsigned integer System.Byte
unsigned short, UINT16, USHORT, WORD, ATOM, WCHAR, __wchar_t 16-bit unsigned integer System.UInt16
unsigned, unsigned int, UINT32, ULONG32, DWORD32, ULONG, DWORD, UINT 32-bit unsigned integer System.UInt32
unsigned __int64, UINT64, DWORDLONG, ULONGLONG 64-bit unsigned integer System.UInt64
float, FLOAT Single-precision floating point System.Single
double, long double, DOUBLE Double-precision floating point System.Double
In Win32 this type is an integer with a specially assigned meaning; in contrast, the CLR provides a specific type devoted to this meaning.
       

 

 转自:http://www.cnblogs.com/bicabo/admin/EditPosts.aspx?opt=1

posted @ 2013-06-06 00:09  Net-Spider  阅读(261)  评论(0)    收藏  举报