• SetForegroundWindow Win32API not always works on Windows7


    BIG NOTE

    After messing with this API for the last 2 months, the solution/s below are all not stable solutions, but they work in some/most cases, depends on your environment, so keep that in mind.

    The solution

    The trick is to make windows ‘think’ that our process and the target window (hwnd) are related by attaching the threads (using AttachThreadInput API) and using an alternative API: BringWindowToTop.
     
    Forcing Window/Internet Explorer to the foreground

    private static void ForceForegroundWindow(IntPtr hWnd)
    {
        uint foreThread = GetWindowThreadProcessId(GetForegroundWindow(), 
            IntPtr.Zero);
        uint appThread = GetCurrentThreadId();
        const uint SW_SHOW = 5;
    if (foreThread != appThread)
        {
            AttachThreadInput(foreThread, appThread, true);
            BringWindowToTop(hWnd);
            ShowWindow(hWnd, SW_SHOW);
            AttachThreadInput(foreThread, appThread, false);
        }
        else
        {
            BringWindowToTop(hWnd);
            ShowWindow(hWnd, SW_SHOW);
        }
    }
    

    A more advanced implementation of AttachedThreadInputAction pattern
    The idea is to attach to the target process thread and preform an action.

    public static void AttachedThreadInputAction(Action action)
    {
        var foreThread = GetWindowThreadProcessId(GetForegroundWindow(), 
            IntPtr.Zero);
        var appThread = GetCurrentThreadId();
        bool threadsAttached = false;
    try
        {
            threadsAttached =
                foreThread == appThread ||
                AttachThreadInput(foreThread, appThread, true);
    if (threadsAttached) action();
            else throw new ThreadStateException("AttachThreadInput failed.");
        }
        finally
        {
            if (threadsAttached)
                AttachThreadInput(foreThread, appThread, false);
        }
    }
    

    Usage

    public const uint SW_SHOW = 5;
    ///<summary>
    /// Forces the window to foreground.
    ///</summary>
    ///hwnd”>The HWND.</param>
    public static void ForceWindowToForeground(IntPtr hwnd)
    {
        AttachedThreadInputAction(
            () =>
            {
                BringWindowToTop(hwnd);
                ShowWindow(hwnd, SW_SHOW);
            });
    }
    public static IntPtr SetFocusAttached(IntPtr hWnd)
    {
        var result = new IntPtr();
        AttachedThreadInputAction(
            () =>
            {
                result = SetFocus(hWnd);
            });
        return result;
    }
    

    Importing Win32-API to do the job

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, 
        out uint lpdwProcessId);
    // When you don't want the ProcessId, use this overload and pass 
    // IntPtr.Zero for the second parameter
    [DllImport("user32.dll")]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, 
        IntPtr ProcessId);
    [DllImport("kernel32.dll")]
    public static extern uint GetCurrentThreadId();
    /// The GetForegroundWindow function returns a handle to the 
    /// foreground window.
    [DllImport("user32.dll")] 
    public static extern IntPtr GetForegroundWindow(); 
    [DllImport("user32.dll")]
    public static extern bool AttachThreadInput(uint idAttach, 
        uint idAttachTo, bool fAttach); 
    [DllImport("user32.dll", SetLastError = true)] 
    public static extern bool BringWindowToTop(IntPtr hWnd); 
    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool BringWindowToTop(HandleRef hWnd); 
    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
    

    Abstract

    After an interesting research, a solution found to force a window to the top in order to simulate user key presses using SendKeys.

    Problem description

    We want to type-keys to simulation user key presses like: strings, enters, tabs…
    We are using SendKeys API. This API require that the wanted target window will be in the foreground and the wanted control will be in focus.
    Seems that since 2007, Vista added  UAC (User Account Control) and , in a nutshell, SetForegroundWindow is not working as expected.
    After researching the problem, the behavior is that calling SetForegroundWindow for the first time fails (returns false).
    After extensive research and readings, it seems that ‘SetForegroundWindow’ have new rules (for security reasons) and the main idea is that ‘An application can’t force another application to be in the foreground, unless it created it or related to it somehow’ (the full rules can be found here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633539(v=vs.85).aspx, see ‘Rules’)

    Resources

  • 相关阅读:
    教你怎样做个有“钱”途的測试project师
    使用具体解释及源代码解析Android中的Adapter、BaseAdapter、ArrayAdapter、SimpleAdapter和SimpleCursorAdapter
    html-上左右布局方式---ShinePans
    POJ1502 MPI Maelstrom Dijkstra
    Angry IP Scanner 获取设备的IP
    【Struts2学习笔记(12)】Struts2国际化
    使用SQL Profile及SQL Tuning Advisor固定运行计划
    sage开发url替换字符串
    柯塔娜大合唱,互联网安全观
    vim水平摆放全部窗体的三个方法
  • 原文地址:https://www.cnblogs.com/tobyqin/p/5549252.html
Copyright © 2020-2023  润新知