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

SetForegroundWindow Win32-API not always works on Windows-7的更多相关文章

  1. C#调用Win32 api学习总结

    从.NET平台调用Win32 API Win32 API可以直接控制Microsoft Windows的核心,因为API(Application Programming Interface)本来就是微 ...

  2. 【.Net】从.NET平台调用Win32 API

    小序        Win32 API可以直接控制Microsoft Windows的核心,因为API(Application Programming Interface)本来就是微软留给我们直接控制 ...

  3. Win32 API编程——前言

    一丶什么是Win32 API? 微软为了保护操作系统的安全性和稳定性,把系统分为内核层和用户层(内核层的代码只能在当CPU的特权级为R0状态下执行,用户层的代码在CPU特权级为R0和R3都能执行),w ...

  4. How to change windows applicatioin's position via Win32 API

    可以使用的Win32 API是: [DllImport("user32.dll")] private extern static bool SetWindowPos(IntPtr ...

  5. WIN32 API ------ 最简单的Windows窗口封装类

    1 开发语言抉择 1.1 关于开发Win32 程序的语言选择 C还是C++ 在决定抛弃MFC,而使用纯Win32 API 开发Window桌面程序之后,还存在一个语言的选择,这就是是否使用C++.C+ ...

  6. 初次认识 C# win32 api

    第一次接触win32api,刚开始的时候有点迷迷糊糊的. Windows API 就是windows应用程序接口. win api向上就是windows应用程序,向下就是windows操作系统核心. ...

  7. Serial Port Programming using Win32 API(转载)

    In this tutorial we will learn How to communicate with an external device like a microcontroller boa ...

  8. 【温故Delphi】GAEA用到Win32 API目录

    Delphi是Windows平台下著名的快速应用程序开发工具,它在VCL中封装并使用了大量的Win32 API. GAEA基于VCL开发的工具类产品,在程序中使用了大量的Win32 API,将经常用到 ...

  9. 【C#】分享基于Win32 API的服务操作类(解决ManagedInstallerClass.InstallHelper不能带参数安装的问题)

    注:这里的服务是指Windows 服务. ------------------201508250915更新------------------ 刚刚得知TransactedInstaller类是支持带 ...

  10. C#中导入Win32 API函数

    C#中导入Win32 API的方法: 1.引用命名空间 using System.Net.Security; using System.Runtime.InteropServices; 2. [Dll ...

随机推荐

  1. IIS宿主WCF服务*.svc Mime类型映射

    经常会遇到由于.net安装组件缺失,导致发布wcf服务后,访问wcf报.svc请求类型不支持 简单方法就是添加删除程序,修改.net组件安装选项,勾选http激活即可: 或者手工添加映射处理程序 1. ...

  2. Spring框架学习之--搭建spring框架

    此文介绍搭建一个最最简单的spring框架的步骤 一.创建一个maven项目 二.在pom.xml文件中添加依赖导入spring框架运行需要的相关jar包 注意:在引入jar包之后会出现org.jun ...

  3. mysql储存过程入门学习

    转载至:https://www.yiibai.com/mysql/getting-started-with-mysql-stored-procedures.html 1.mysql储存过程的创建 DE ...

  4. 支持Linux系统的加密狗

    深思数盾 https://www.sense.com.cn/ 产品:精锐5 版本:标准版.精灵版.IE版.时钟锁 快速实现高安全度的软件保护,轻松定义多种授权模式1.防止软件盗版,防止逆向工程 通过增 ...

  5. Java博客目录

    JavaWeb 1.Tomcat使用 2.Servlet入门 3.JSP&EL&JSTL 4.Listener&Filter Java框架 Hibernate 1.简介及初使用 ...

  6. JAVA反射机制及理解

    JAVA反射 往往当我们面对一项新的知识时,我们往往需要知道三个方面,它是什么,它能做什么,它比原有知识强在哪里,我们该怎么使用它.当你能够解决这些问题时,便意味着你已经对这项知识入门了. 首先: 反 ...

  7. JavaScript实现RSA加解密

    在GitHub上找到jsencrypt.js对RSA加解密的工具文件,地址分别是:https://github.com/travist/jsencrypt和https://github.com/ope ...

  8. postman headers 请求参数和MD5加密签名

    postman 变量可以这样写:{{timestamp}} ,也可以用系统的,{{$timestamp}},这样就不用给自己赋值了,但在 pre-requestScript中是获取不到这个值的 所以我 ...

  9. Linux批量结束、杀死进程

    ps aux|grep python|grep -v grep|cut -c 9-15|xargs kill -15 管道符“|”用来隔开两个命令,管道符左边命令的输出会作为管道符右边命令的输入.下面 ...

  10. js 闭包,作用域,this 终结篇(转)

    之前有写过闭包,作用域,this方面的文章,但现在想想当时写的真是废话太多了,以至于绕来绕去的,让新手反而更难理解了,所以就有了此篇文章,也好和闭包,作用域,this告一段落. 第一个问题:什么是闭包 ...