一个在c#中 调用API的例子

这段时间开始玩C#,在学习中发现有时候需要调用win32 APi时候,是如此的麻烦,真是烦这个C#跟个白痴样的,一点都不喜欢用,不是项目需要 才懒得看它一眼

言归正传,花了好几个小时,搜索大量资料才搞定了这一个例子,写在这里,以后都照这个模子刻了

 

1.第一步记得在项目------》属性----->生成------->勾选不安全代码

这个选项一定要勾选 因为在c#中调用api函数是非托管代码,属于不安全代码

 

2.在文件最上面加入using System.Runtime.InteropServices;

 

3.在调用前,加入一下内容:

 

const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const uint OPEN_EXISTING = 3;
const uint CREATE_NEW = 4;
const uint CREATE_ALWAYS = 5;

 

以上是自己要用的函数参数的定义。知道在c#中麻烦了吧,参数还要自己定义值

接着:

[DllImport("kernel32.dll", SetLastError = true)]后面的setlastError不一定要

再接着

static extern unsafe System.IntPtr CreateFile(

string lpFileName,

uint dwDesiredAccess,

uint dwShareMode,

uint lpSecurityAttributes,

uint dwCreationDisposition,

uint dwFlagsAndAttributes,

int hTemplateFile);

这里相当于函数在使用前的声明。注意有个unsafe,不明白的,查资料

可以注意到每个参数的类型都变了,这是因为在c#中是不同的,请参照相关c#数据修改原参数类型

 

后面就是调用了

 

System.IntPtr handle;

      handle = CreateFile(st, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);

 if (handle != System.IntPtr.Zero)
           {
               //return true;
           }
           else
           {
               //return false;
           }

 

完整代码如下:

 

 

 const uint GENERIC_READ = 0x80000000;
        const uint GENERIC_WRITE = 0x40000000;
        const uint OPEN_EXISTING = 3;
        const uint CREATE_NEW = 4;
        const uint CREATE_ALWAYS = 5;
       

        [DllImport("kernel32.dll", SetLastError = true)]
       

static extern unsafe System.IntPtr CreateFile(

string lpFileName,

uint dwDesiredAccess,

uint dwShareMode,

uint lpSecurityAttributes,

uint dwCreationDisposition,

uint dwFlagsAndAttributes,

int hTemplateFile);  

 

      

        static void Main(string[] args)
        {
            string st = ".//CreateFileDemo.txt";

 

            System.IntPtr handle;

 

 handle = CreateFile(st, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);

 

                        if (handle != System.IntPtr.Zero)
           {
               //return true;
           }
           else
           {
               //return false;
           }

 

 

行了,以后照这个Ctrl+v就行了,再有意外再想办法。BS C#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值