65.9K
CodeProject 正在变化。 阅读更多。
Home

按键扩展器(兼容 Win 7)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.30/5 (6投票s)

2009年4月19日

GPL3

1分钟阅读

viewsIcon

22633

downloadIcon

619

像 Windows 7 一样使用快捷键处理 Windows。

引言

在 Windows 7 中,我非常喜欢使用 Win + (左 | 右 | 上 | 下) 快捷键来改变窗口位置。

  • Win + 左 - 窗口停靠到左侧
  • Win + 右 - 窗口停靠到右侧
  • Win + 上 - 窗口最大化
  • Win + 下 - 窗口恢复到正常状态

 

Using the Code

让这个功能在 Windows Vista 上工作(很可能在早期版本中也能工作,但我没有尝试过)并不是一件难事。首先,我在一个 WinForms 应用程序中导入了许多 WinApi 函数。这项工作分为两部分:

  1. 拦截按键,以及
  2. 定位活动窗口

这篇文章 C# 中的低级别键盘钩子 帮助我解决了第一部分。我只需要找到判断 LWin 按钮是否被按下的方法。以下是主要代码:

private static IntPtr HookCallback(
    int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WAKeysHook.WmKeyDown)
    {
        if ((int)WAKeysHook.GetAsyncKeyState((IntPtr)Keys.LWin) != 0) // Left Win Key
        {
            Keys key = (Keys) Marshal.ReadInt32(lParam);
            if (key == Keys.Left || key == Keys.Right || 
		key == Keys.Up || key == Keys.Down) // Arrows keys
                SetWindowLocation(key);
        }
    }
    return WAKeysHook.CallNextHookEx(WaKeysHook.HookId, nCode, wParam, lParam);
} 

第二部分:查找前台窗口,设置状态和大小。

private static void SetWindowLocation(Keys k)
{
    //Active Window
    IntPtr window = WAWindows.GetForegroundWindow();
    // Check SIZEBOX Style (Window can sizable)
    if (((int)WAWindows.GetWindowLongPtr(window, WAWindows.GwlStyle) & 
	WAWindows.WsSizebox)
        == WAWindows.WsSizebox)
    {
        // Show window in normal state (if always maximized)
        WAWindows.ShowWindow(window, (int)WAWindows.WindowShowStyle.ShowNormal);
        
        //Need Maximized
        if (k != Keys.Down)
        {
            WAWindows.ShowWindow(window, (int)WAWindows.WindowShowStyle.ShowMaximized);

            // Place Window on left or right
            if (k != Keys.Up)
            {
                WAWindows.Rect rect, rectDesktop;
                if (WAWindows.GetWindowRect(window, out rect) && 
		WAWindows.GetWindowRect(WAWindows.GetDesktopWindow(), 
		out rectDesktop))
                {
                    WAWindows.SetWindowPos(window, WAWindows.HwndTop, 
			(k == Keys.Left) ? Math.Min(rect.Left, 0) : 
			rectDesktop.Right / 2, rect.Top, Math.Min(rect.Width, 
			rectDesktop.Right / 2 - Math.Min(rect.Left, 0)),
                                 Math.Min(rect.Height, rectDesktop.Bottom), 
				WAWindows.SwpShowwindow);
                }
            }
        }
    }
}

此外,还有一个机会可以在任务栏中显示(或隐藏)图标,并带有上下文菜单(这可以帮助您关闭应用程序)。您可以在 app.config 的 "ShowNotifyIcon" 部分设置这些选项。

<applicationSettings>
    <VistaKeysExtender.Properties.Settings>
        <setting name="ShowNotifyIcon" serializeAs="String">
            <value>False</value>
        </setting>
    </VistaKeysExtender.Properties.Settings>
</applicationSettings>

尽情享受吧!

更新时间

  • 2009-04-20 - 为 x64 系统构建版本
  • 2009-04-21 - 项目有新版本。现在您可以选择设置,并且修复了一些错误。这是新版本的窗口
0000k00h.png

您可以从 这里 下载新版本和代码。

© . All rights reserved.