ntwain/NTwain/Internals/WindowsHook.cs

77 lines
2.1 KiB
C#
Raw Normal View History

using NTwain.Interop;
using System;
2014-09-05 18:56:57 +08:00
using System.Diagnostics;
2014-04-21 04:57:38 +08:00
using System.Runtime.InteropServices;
using System.Windows.Interop;
namespace NTwain.Internals
{
/// <summary>
2014-09-03 07:10:35 +08:00
/// Abstracts out wnd proc hook on Windows from InternalMessageLoopHook class.
2014-04-21 04:57:38 +08:00
/// This allows things to not depend on PresentationCore.dll at runtime on mono.
/// </summary>
class WindowsHook : IDisposable
{
IDisposable _win;
IWinMessageFilter _filter;
2014-04-21 04:57:38 +08:00
public WindowsHook(IWinMessageFilter filter)
2014-04-21 04:57:38 +08:00
{
_filter = filter;
2014-04-21 04:57:38 +08:00
HwndSource win = null;
try
{
2014-09-05 18:56:57 +08:00
// hook into windows msg loop for old twain to post msgs.
// the style values are purely guesses here with
// CS_NOCLOSE, WS_TILEDWINDOW, and WS_EX_APPWINDOW
win = new HwndSource(0x0200, 0xCF0000, 0x40000, 0, 0, "NTWAIN_LOOPER", IntPtr.Zero);
2014-04-21 04:57:38 +08:00
Handle = win.Handle;
win.AddHook(WndProc);
_win = win;
}
catch
{
if (win != null) { win.Dispose(); }
2014-04-21 08:45:08 +08:00
throw;
2014-04-21 04:57:38 +08:00
}
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (_filter != null)
2014-04-21 04:57:38 +08:00
{
handled = _filter.IsTwainMessage(hwnd, msg, wParam, lParam);
2014-04-21 04:57:38 +08:00
}
2014-09-05 18:56:57 +08:00
if (!handled)
{
Debug.WriteLine("Hwnd=" + hwnd);
handled = true;
// unnecessary to do default wndproc?
return NativeMethods.DefWindowProc(hwnd, (uint)msg, wParam, lParam);
}
2014-04-21 04:57:38 +08:00
return IntPtr.Zero;
}
public IntPtr Handle { get; private set; }
#region IDisposable Members
public void Dispose()
{
if (_win != null)
{
((HwndSource)_win).RemoveHook(WndProc);
_win.Dispose();
_win = null;
2014-09-05 18:56:57 +08:00
Handle = IntPtr.Zero;
2014-04-21 04:57:38 +08:00
}
}
#endregion
}
}