未能添加对“*.dll”的引用

引用dll时,报了如下错误

未能添加对“*.dll”的引用。请确保此文件可访问并且是一个有效的程序集或 COM 组件。

原因是,.net 只能引用托管的dll,非托管的native dll,可以用 DllImport导入其中的函数进行调用。不需要在项目里添加引用,只要把dll和你的程序放在同一个文件夹下即可。

下面的代码示例演示如何使用DllImportAttribute特性导入Win32MessageBox函数。然后,该代码示例调用导入的方法。

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(IntPtr hWnd,String text,String caption,uint type);

        static void Main(string[] args)
        {
            MessageBox(new IntPtr(0),"Hello World!","Hello Dialog",0);
        }
    }
}










参考资料:https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.interopservices.dllimportattribute?redirectedfrom=MSDN&view=netframework-4.7.2

猜你喜欢

转载自www.cnblogs.com/fanful/p/12263772.html