public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public static RECT FromRectangle(Rectangle rc)
{
RECT RCTO = new RECT();
RCTO.left = rc.Left;
RCTO.top = rc.Top;
RCTO.right = rc.Right;
RCTO.bottom = rc.Bottom;
return RCTO;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public POINT(Point point)
{
this.x = point.X;
this.y = point.Y;
}
public Point ToPoint()
{
return new Point(this.x, this.y);
}
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct WINDOWPLACEMENT
{
public uint length;
public uint flags;
public uint showCmd;
public POINT ptMinPosition;
public POINT ptMaxPosition;
public RECT rcNormalPosition;
}
系统快捷键,需要使用一个自定义类,调用系统 API 实现。
public class AppHotKey : System.Windows.Forms.NativeWindow, IDisposable
{
// Error codes
const int ERROR_HOTKEY_ALREADY_REGISTERED = 1409;
// Member variables
private int m_AtomID = 0;
private bool registerSuccess;
private KeyModifiers hotKeyMod;
private Keys hotKey;
public AppHotKey(IntPtr handle, KeyModifiers modifiers, Keys hotKey)//
{
if (!WindowsAPI.IsWindow(handle))
throw new ArgumentException();
this.hotKey = hotKey;
this.hotKeyMod = modifiers;
this.AssignHandle(handle);
m_AtomID = WindowsAPI.GlobalAddAtom(DateTime.Now.ToString());
registerSuccess = WindowsAPI.RegisterHotKey(handle, m_AtomID, modifiers, hotKey);
if (!registerSuccess)
{
if (WindowsAPI.GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED)
throw new InvalidOperationException();
}
}
~AppHotKey()
{
this.Dispose(false);
}
public Keys HotKey
{
get
{
return hotKey;
}
}
public KeyModifiers ModifierKey
{
get
{
return hotKeyMod;
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
lock(this)
{
if (disposing)
{
}
try
{
// Unregister the hotkey.
if (registerSuccess)
WindowsAPI.UnregisterHotKey(this.Handle, m_AtomID);
if (m_AtomID != 0)
{
// Delete Atom
WindowsAPI.GlobalDeleteAtom(m_AtomID);
m_AtomID = 0;
}
}
catch
{
}
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch(m.Msg)
{
case (int)Msg.WM_HOTKEY:
this.ProcessHotKey();
break;
}
}
protected virtual void ProcessHotKey()
{
WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
wp.length = (uint)Marshal.SizeOf(typeof(WINDOWPLACEMENT));
WindowsAPI.GetWindowPlacement(this.Handle, ref wp);
//Make sure the window is not minimized or maximized
if (wp.showCmd == (uint)ShowWindowStyles.SW_SHOWMAXIMIZED)
WindowsAPI.ShowWindowAsync(this.Handle,(short)ShowWindowStyles.SW_MAXIMIZE);
else
WindowsAPI.ShowWindowAsync(this.Handle,(short)ShowWindowStyles.SW_SHOWNORMAL);
//Set the real intance to foreground window
WindowsAPI.SetForegroundWindow(this.Handle);