在本机代码中有以下内容,需要使用托管代码编写:
HINSTANCE hUser = LoadLibrary("user32.dll"); /* Can't fail -- it's already loaded */
BOOL (*dpi)() = (BOOL (*)())GetProcAddress(hUser, "SetProcessDPIAware");
if(dpi) dpi();
我们支持的最低端平台上不存在函数SetProcessDPIAware,因此我们只是在声明函数并尝试调用它时遇到加载器问题。
但是,我必须根据操作系统版本以外的条件做出运行时决定是否调用SetProcessDPIAware,这样我才能使用清单。
答案 0 :(得分:1)
你可以用类似的方式P /调用LoadLibrary
和GetProcAddress
:
using System;
using System.Runtime.InteropServices;
static class Program
{
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
delegate bool MyDelegate();
static void Main()
{
var hUser = LoadLibrary("user32.dll");
var res = GetProcAddress(hUser, "SetProcessDPIAware");
if (res != IntPtr.Zero)
{
// The function we are looking for exists =>
// we can now get the corresponding delegate and invoke it
var del = (MyDelegate)Marshal.GetDelegateForFunctionPointer(res, typeof(MyDelegate));
bool x = del();
Console.WriteLine(x);
}
}
}