如何关注最后激活的程序?

时间:2012-12-01 13:37:06

标签: .net windows vb.net winforms focus

如果您正在制作Windows窗体应用程序并且打开了“记事本”和“Web浏览器”,那么如何在应用程序获得焦点之前将焦点放在最后一个焦点上?

2 个答案:

答案 0 :(得分:3)

按Alt + Tab键可以让您返回之前的活动窗口。它是代码中的一行代码:

    SendKeys.Send("%{TAB}")

答案 1 :(得分:1)

您可以使用回调函数和一组API来查找可以通过Alt-Tab查看的程序列表(打开的窗口)(无需查看Alt-Tab窗口)。

首先声明要使用的API集合:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern int EnumWindows(CallBackPtr callPtr, int lPar);

[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern bool SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder         lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wparam, int lparam);

const int WM_GETTEXT = 0xD;

private static int windowCount = 0;

然后你需要通过窗口枚举并激活最后一个:

public static bool EnumWindowProc(int hwnd, int lParam)
{
    if (!IsWindowVisible((IntPtr)hwnd) || GetWindow((IntPtr)hwnd, GW_OWNER) != IntPtr.Zero)
    return true;

    string name = GetWindowTextRaw((IntPtr)hwnd);
    if (name.Length > 0)
    {
        windowCount++;
        if (windowCount == 2) //The previouse active window
        {
            SetForegroundWindow((IntPtr)hwnd);
            return false;
        }
    }


    return true;
}

并使用以下代码检索窗口的名称。

public static string GetWindowTextRaw(IntPtr hwnd)
{
    var length = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0);
    var sb = new StringBuilder(length + 1);
    SendMessage(hwnd, WM_GETTEXT, sb.Capacity, sb);
    return sb.ToString();
}

最后调用以下函数:

public void ActivateLastWindow()
{
    callBackPtr = EnumWindowProc;
    windowCount = 0;
    EnumWindows(callBackPtr, 0);
}