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
VBaisc例子
方法一。
<DllImport("user32.dll")> _
Public Shared Function SetWindowPos(ByVal hWnd As IntPtr, ByVal hWndInsertAfter As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As Integer) As Boolean
End Function
<DllImport("KERNEL32.DLL", EntryPoint:="MoveFileW", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function MoveFile(ByVal src As String, ByVal dst As String) As Boolean
' This function copies a file from the path src to the path dst.
' Leave function empty - DLLImport attribute forces calls
' to MoveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function
方法二
Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
详细例子可见另一篇文章
VB.NET编程中调用Windows API
本文来自: 中国网管联盟(bitsCN.com) 详细出处参考:http://www.bitscn.com/dotnet/vb/200605/24574.html
VB.Net查看文件中图标的函数及申明Windows API的方法
本文来自: 中国网管联盟(bitsCN.com) 详细出处参考:http://www.bitscn.com/dotnet/vb/200605/24574.html
附1常用Win32数据类型与.NET平台数据类型的对应表
Figure 2 Non-Pointer Data Types
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. |