public class PrintScreen : Window
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
IntPtr handle = new WindowInteropHelper(this).Handle;
if (handle != (IntPtr)0) // can happen in unit tests
{
src = HwndSource.FromHwnd(handle);
src.AddHook(WindowsMsgHook);
RegisterPrintScreenKeyStroke();
}
}
// Register the Alt+PrintScreen hot key.
private void RegisterPrintScreenKeyStroke()
{
if(printScreenHKey == null)
{
printScreenHKey = new HotKey();
printScreenHKey.Modifier = ModifierKeys.Alt;
printScreenHKey.Key = Forms.Keys.PrintScreen;
printScreenHKey.ToRegisterHotKey();
}
}
private IntPtr WindowsMsgHook( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Checks whether the window message is hotkey message.
if(msg == WM_HOTKEY)
{
//The high-order word specifies the virtual key code of the hot key.
int vkey = (((int)lParam >> 16) & 0xFFFF);
if (!handled && vkey == (uint)Forms.Keys.PrintScreen)
{
handled = true;
PrintScreenPressed();
}
}
return (IntPtr)0;
}
public const int WM_HOTKEY = 0x0312;
}
我编写了一个代码来截取主屏幕的截图,该主屏幕使用窗口的句柄来注册热键。现在,我想编写单元测试来测试这段代码。你能给出写UT的想法。
热键是另一个类。
公共类HotKey {
public HotKey()
{
winHandle = this.Instance.Handle;
winHashCode = this.Instance.GetType().GetHashCode();
}
public System.Windows.Input.ModifierKeys Modifier { get; set; }
public System.Windows.Forms.Keys Key { get; set; }
///<summary>
/// Method uses User32 API function to register hot keystrokes.
///</summary>
public void ToRegisterHotKey()
{
ToUnregisterHotKey();
if (!isRegistered && winHandle != IntPtr.Zero)
{
if (RegisterHotKey(winHandle, winHashCode,(uint)Modifier, (uint)Key))
{
isRegistered = true;
}
}
}
public void ToUnregisterHotKey()
{
if (isRegistered && winHandle != IntPtr.Zero)
{
if (!UnregisterHotKey(winHandle, winHashCode))
//Error logging
isRegistered = false;
}
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr wndHandle, int id, uint modifier, uint key);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private IntPtr winHandle;
private int winHashCode;
private bool isRegistered;
}