DLL中的回调(Windows API)?

时间:2018-02-02 01:42:43

标签: c# pinvoke

我需要编写一个与winmm.dll接口的库。

https://msdn.microsoft.com/en-us/library/windows/desktop/dd798458(v=vs.85).aspx

public static class winmm {
...
   [DllImport("winmm.dll", SetLastError = true)]
   public static extern uint midiInOpen(out UIntPtr lphMidiIn, uint
      uDeviceID, UIntPtr dwCallback, UIntPtr dwCallbackInstance, uint dwFlags);
...
}
public void MidiInOpen() {
   winmm.midiInOpen(out midiHdl, (uint)deviceId, CALLBACK, CALLBACKINSTANCE, FLAG);
}

public void midiInCallback() {
      ...
 }

如何设置dwCallbackdwCallbackInstance参数?

1 个答案:

答案 0 :(得分:1)

关于dwCallback使用delegate

<强>设置

[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiInOpen(out HMIDIIN lphMidiIn, UIntPtr uDeviceID,
        MidiInProc dwCallback, UIntPtr dwCallbackInstance, MidiOpenFlags dwFlags);

[StructLayout(LayoutKind.Sequential)]
public struct HMIDIIN
{
   public IntPtr handle;
}

public enum MMRESULT : uint
{
   // General return codes.
   MMSYSERR_BASE = 0,
   MMSYSERR_NOERROR = MMSYSERR_BASE + 0,
   ...
}

public enum MidiOpenFlags : uint
{
   CALLBACK_TYPEMASK = 0x70000,
   CALLBACK_NULL = 0x00000,
   ...
}

public enum MidiInMessage : uint
{
   MIM_OPEN = 0x3C1,
   MIM_CLOSE = 0x3C2,
   ...
}

委派

public delegate void MidiInProc(HMIDIIN hMidiIn, MidiInMessage wMsg, UIntPtr dwInstance, UIntPtr dwParam1, UIntPtr dwParam2);

用法

MidiInProc dwCallback ...

public static MMRESULT midiInOpen(out HMIDIIN lphMidiIn, UIntPtr uDeviceID, MidiInProc dwCallback, UIntPtr dwCallbackInstance)
{
   return midiInOpen(out lphMidiIn, uDeviceID, dwCallback, dwCallbackInstance, dwCallback == null ? MidiOpenFlags.CALLBACK_NULL : MidiOpenFlags.CALLBACK_FUNCTION);
}

关于dwCallbackInstance使用GCHandle

midiInOpen function

  

dwCallbackInstance 传递给回调函数的用户实例数据。此参数不与窗口回调函数一起使用   线程。

How To Convert Object To IntPtr And Back?

How can an UIntPtr object be converted to IntPtr in C#?

简而言之,有很多适用于Windows API主题的资源