add SystemMenuHook

This commit is contained in:
NaBian committed 2019-08-21 21:48:05 +08:00
1 parent a9720f080b
commit 3d32e17afd
15 files changed
+236 -219

No files matched your search

@@ -1,5 +1,4 @@
using System;
using System.Windows;
using System.Windows.Interop;
using HandyControl.Tools.Interop;
@@ -20,7 +19,7 @@ namespace HandyControl.Tools
Stop();
}
HookId = new WindowInteropHelper(new Window()).EnsureHandle();
HookId = WindowHelper.CreateHandle();
HWndSource = HwndSource.FromHwnd(HookId);
if (HWndSource != null)
{
@@ -29,7 +28,11 @@ namespace HandyControl.Tools
}
}
public static void Stop() => NativeMethods.RemoveClipboardFormatListener(HookId);
public static void Stop()
{
HWndSource.RemoveHook(WinProc);
NativeMethods.RemoveClipboardFormatListener(HookId);
}
private static IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
{
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Interop;
using HandyControl.Tools.Interop;
namespace HandyControl.Tools
{
public class SystemMenuHook
{
private static readonly Dictionary<int, HwndSource> DataDic = new Dictionary<int, HwndSource>();
public static event EventHandler<int> Click;
public static void Insert(int index, int id, string text, Window window)
{
var hookId = window.GetHandle();
var source = HwndSource.FromHwnd(hookId);
if (source != null)
{
DataDic[id] = source;
NativeMethods.InsertMenu(NativeMethods.GetSystemMenu(hookId, false), index, NativeMethods.MF_BYPOSITION, id, text);
source.AddHook(WinProc);
}
}
public static void InsertSeperator(int index, Window window) => NativeMethods.InsertMenu(
NativeMethods.GetSystemMenu(window.GetHandle(), false), index,
NativeMethods.MF_BYPOSITION | NativeMethods.MF_SEPARATOR, 0, "");
public static void Remove(int id)
{
if (DataDic.TryGetValue(id, out var data))
{
data.RemoveHook(WinProc);
DataDic.Remove(id);
}
}
private static IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
{
if (msg == NativeMethods.WM_SYSCOMMAND)
{
var id = wparam.ToInt32();
if (DataDic.ContainsKey(id))
{
Click?.Invoke(null, id);
}
}
return IntPtr.Zero;
}
}
}