Calling DLL from C#: the retrace problem half solved
More code bits. Trying to determine refresh retrace signal on a monitor using C#, I had to import the DLPortIO library, which let me bypass the Windows securities and access IO ports directly. Trouble is the DLL is not an ActiveX or COM object. so what I needed was to
This example demonstrates how to call a function exported from an unmanaged library from managed code. The MessageBox routine in User32.dll and GetSystemTime routine in Kernel32.dll are called. The same technique can be used to call any exported function in any other library.
In order to call MessageBox and GetSystemTime, you need the metadata that describes each method and its arguments. The necessary metadata is provided by defining a managed class with one or more static methods. The class and the static methods can have any name you choose. You might want to create several classes that contain related functions or simply group all the functions you need into a single class.
In C# the DllImport attribute is used to identify the name of the actual DLL that contains the exported function. The method must be defined as static and external in order to apply the attribute.
C#If the name of the method is different than the actual export name in the DLL, the DllImport.EntryPoint property can be used to map the function to the correct entry point if you are using C#. In Visual Basic you can use Alias keyword for this purpose.
using System.Runtime.InteropServices;public class Win32 {
…
[DllImport("User32.dll", EntryPoint="MessageBox", CharSet=CharSet.Auto)]
public static extern int MsgBox(int hWnd, String text, String caption, uint type);
}public class TestPInvoke {
public static void Main() {
…
String date = …;Win32.MsgBox(0, date, "PInvoke Sample", 0);
}
}
What I ended up with is really simple:
# region utillity components
// to call DLL directly.
public class dllIO {
// DlPortIO.dll
[DllImport("DLPORTIO.dll", EntryPoint = "DlPortReadPortUchar", CharSet = CharSet.Auto)]
public static extern int DlPortReadPortUchar(char port);
}
# endregion
…
int retrace = dllIO.DlPortReadPortUchar((char)0×3da);
This will give "1" when it’s in retrace and "0" if it’s not (I think, needed to confirm with more test). So to wait for retrace, simply wait for it to turn from 0 to 1.
See this article for a more dynamic, albeit complex, way to invoke a DLL. The comments point to other articles on CodeProjects.
To-do: How do I generate a retrace event?