-1

Have the following in native code, need to write in managed code:

HINSTANCE hUser = LoadLibrary("user32.dll"); /* Can't fail -- it's already loaded */
BOOL (*dpi)() = (BOOL (*)())GetProcAddress(hUser, "SetProcessDPIAware");
if(dpi) dpi();

The function SetProcessDPIAware does not exist on the lowest end platform we support, so we would run into loader problems simply declaring the function and trying to call it.

However, I have to make a runtime decision whether or not to call SetProcessDPIAware based on conditions other than operating system version so I cannot use a manifest.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Joshua
  • 40,822
  • 8
  • 72
  • 132

1 Answers1

1

You could P/Invoke the LoadLibrary and GetProcAddress in a similar way:

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);
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928