扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:肄若芸 来源:csdn 2007年11月13日
关键字: Visual C# Windows API 要点
using System.Runtime.InteropServices; //引用此名称空间,简化后面的代码 ... //使用DllImportAttribute特性来引入api函数,注意声明的是空方法,即方法体为空。 [DllImport("user32.dll")] public static extern ReturnType FunctionName(type arg1,type arg2,...); //调用时与调用其他方法并无区别 |
[ DllImport( "kernel32", EntryPoint="GetVersionEx" )] |
[DllImport("user32.dll",CharSet="CharSet.Auto",EntryPoint="MessageBox")] public static extern int MsgBox(IntPtr hWnd,string txt,string caption, int type); |
[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)] public class MySystemTime { [FieldOffset(0)]public ushort wYear; [FieldOffset(2)]public ushort wMonth; [FieldOffset(4)]public ushort wDayOfWeek; [FieldOffset(6)]public ushort wDay; [FieldOffset(8)]public ushort wHour; [FieldOffset(10)]public ushort wMinute; [FieldOffset(12)]public ushort wSecond; [FieldOffset(14)]public ushort wMilliseconds; } |
/********************************************** * API中定义原结构声明 * OSVERSIONINFOA STRUCT * dwOSVersionInfoSize DWORD ? * dwMajorVersion DWORD ? * dwMinorVersion DWORD ? * dwBuildNumber DWORD ? * dwPlatformId DWORD ? * szCSDVersion BYTE 128 dup (?) * OSVERSIONINFOA ENDS * * OSVERSIONINFO equ <OSVERSIONINFOA> *********************************************/ //.net中声明为类 [ StructLayout( LayoutKind.Sequential )] public class OSVersionInfo { public int OSVersionInfoSize; public int majorVersion; public int minorVersion; public int buildNumber; public int platformId; [ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )] public String versionString; } //或者 //.net中声明为结构 [ StructLayout( LayoutKind.Sequential )] public struct OSVersionInfo2 { public int OSVersionInfoSize; public int majorVersion; public int minorVersion; public int buildNumber; public int platformId; [ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )] public String versionString; } |
[MarshalAs(UnmanagedType.LPStr)] String existingfile; [MarshalAs(UnmanagedType.LPStr)] String newfile; |
[ DllImport( "kernel32", EntryPoint="GetVersionEx" )] public static extern bool GetVersionEx2( ref OSVersionInfo2 osvi ); |
FileStream fs = new FileStream( "a.txt", FileMode.Open ); StringBuilder buffer = new StringBuilder( 5 ); int read = 0; ReadFile(fs.Handle, buffer, 5, out read, 0 ); //调用Win API中的ReadFile函数 |
[ DllImport( "Kernel32.dll" )] public static extern bool ReadFile( HandleRef hndRef, StringBuilder buffer, int numberOfBytesToRead, out int numberOfBytesRead, ref Overlapped flag ); ...... ...... FileStream fs = new FileStream( "HandleRef.txt", FileMode.Open ); HandleRef hr = new HandleRef( fs, fs.Handle ); StringBuilder buffer = new StringBuilder( 5 ); int read = 0; // platform invoke will hold reference to HandleRef until call ends ReadFile( hr, buffer, 5, out read, 0 ); |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者