http://forums.codeguru.com/showthread.php?392273-RESOLVED-How-to-get-window-s-HWND-from-it-s-process-handle

I am confused about what you know and what you still need to know. Some of your statements seem to be contradicting, so I will tell you some possibilities:

1)
HAVE: Process ID, NEED: Process handle
Solution: OpenProcess()

2)
HAVE: Process handle, NEED: Process ID
Solution: GetProcessId()

3)
HAVE: Window handle, NEED: Process ID
Solution: GetWindowThreadProcessId()

4)
HAVE: Window handle, NEED: Process handle
Solution: Use 3) and then 1)

5)
HAVE: Process ID, NEED: Window handle
Solution: EnumWindows(), then in the callback function do 3) and check if it matches your process ID.

6)
HAVE: Process handle, NEED: Window handle
Solution: 2) and then 5)

http://www.programlife.net/get-main-window-handler-in-dll.html

有的时候难免需要在DLL中获取主进程的窗口句柄,比如在DLL注入的时候等等。那么如何在DLL中获取主进程的窗口句柄呢?可以通过EnumWindows来实现。先通过GetCurrentProcessId获取进程的PID,然后在EnumWindows中调用GetWindowThreadProcessId获得与窗口句柄关联的进程PID,然后对比PID,看是否相等,并判断是不是主窗口即可。
以上方法参考自网络,不一定很完善,但是通常情况下已经够用了。附上测试代码:

// Author: 代码疯子
// Blog: http://www.programlife.net/
#include <windows.h> BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
DWORD dwCurProcessId = *((DWORD*)lParam);
DWORD dwProcessId = ; GetWindowThreadProcessId(hwnd, &dwProcessId);
if(dwProcessId == dwCurProcessId && GetParent(hwnd) == NULL)
{
*((HWND *)lParam) = hwnd;
return FALSE;
}
return TRUE;
} HWND GetMainWindow()
{
DWORD dwCurrentProcessId = GetCurrentProcessId();
if(!EnumWindows(EnumWindowsProc, (LPARAM)&dwCurrentProcessId))
{
return (HWND)dwCurrentProcessId;
}
return NULL;
} BOOLEAN WINAPI DllMain(
IN HINSTANCE hDllHandle,
IN DWORD nReason,
IN LPVOID Reserved)
{
BOOLEAN bSuccess = TRUE; switch ( nReason )
{
case DLL_PROCESS_ATTACH:
MessageBox(GetMainWindow(), TEXT("OMG~ You are Attacked!"), TEXT("Warning"), MB_ICONWARNING);
break; case DLL_PROCESS_DETACH:
break;
} return bSuccess;
}

ProcessID, Process Handle, Window Handle 之间的互相转换

http://www.delphitop.com/html/jincheng/219.html

// Get ProcessID By ProgramName (Include Path or Not Include)
function GetPIDByProgramName(const APName: string): THandle;
// Get Window Handle By ProgramName (Include Path or Not Include)
function GetHWndByProgramName(const APName: string): THandle;
// Get Window Handle By ProcessID
function GetHWndByPID(const hPID: THandle): THandle;
// Get ProcessID By Window Handle
function GetPIDByHWnd(const hWnd: THandle): THandle;
// Get Process Handle By Window Handle
function GetProcessHndByHWnd(const hWnd: THandle): THandle;
// Get Process Handle By Process ID
function GetProcessHndByPID(const hAPID: THandle): THandle;
// Get Window Handle By ProgramName (Include Path or Not Include)
function GetHWndByProgramName(const APName: string): THandle;
begin
Result:=GetHWndByPID(GetPIDByProgramName(APName));
end; // Get Process Handle By Window Handle
function GetProcessHndByHWnd(const hWnd: THandle): THandle;
var
PID: DWORD;
AhProcess: THandle;
begin
if hWnd<> then
begin
GetWindowThreadProcessID(hWnd, @PID);
AhProcess := OpenProcess(PROCESS_ALL_ACCESS, false, PID);
Result:=AhProcess;
CloseHandle(AhProcess);
end
else
Result:=;
end; // Get Process Handle By Process ID
function GetProcessHndByPID(const hAPID: THandle): THandle;
var
AhProcess: THandle;
begin
if hAPID<> then
begin
AhProcess := OpenProcess(PROCESS_ALL_ACCESS, false, hAPID);
Result:=AhProcess;
CloseHandle(AhProcess);
end
else
Result:=;
end; // Get Window Handle By ProcessID
function GetPIDByHWnd(const hWnd: THandle): THandle;
var
PID: DWORD;
begin
if hWnd<> then
begin
GetWindowThreadProcessID(hWnd, @PID);
Result:=PID;
end
else
Result:=;
end; // Get Window Handle By ProcessID
function GetHWndByPID(const hPID: THandle): THandle;
type
PEnumInfo = ^TEnumInfo;
TEnumInfo = record
ProcessID: DWORD;
HWND: THandle;
end; function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): Bool; stdcall;
var
PID: DWORD;
begin
GetWindowThreadProcessID(Wnd, @PID);
Result := (PID <> EI.ProcessID) or
(not IsWindowVisible(WND)) or
(not IsWindowEnabled(WND)); if not Result then EI.HWND := WND; //break on return FALSE 所以要反向檢查
end; function FindMainWindow(PID: DWORD): DWORD;
var
EI: TEnumInfo;
begin
EI.ProcessID := PID;
EI.HWND := ;
EnumWindows(@EnumWindowsProc, Integer(@EI));
Result := EI.HWND;
end;
begin
if hPID<> then
Result:=FindMainWindow(hPID)
else
Result:=;
end; // Get ProcessID By ProgramName (Include Path or Not Include)
function GetPIDByProgramName(const APName: string): THandle;
var
isFound: boolean;
AHandle, AhProcess: THandle;
ProcessEntry32: TProcessEntry32;
APath: array[..MAX_PATH] of char;
begin
try
Result := ;
AHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, );
ProcessEntry32.dwSize := Sizeof(ProcessEntry32);
isFound := Process32First(AHandle, ProcessEntry32); while isFound do
begin
AhProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,
false, ProcessEntry32.th32ProcessID);
GetModuleFileNameEx(AhProcess, , @APath[], sizeof(APath)); if (UpperCase(StrPas(APath)) = UpperCase(APName)) or
(UpperCase(StrPas(ProcessEntry32.szExeFile)) = UpperCase(APName)) then
begin
Result := ProcessEntry32.th32ProcessID;
break;
end;
isFound := Process32Next(AHandle, ProcessEntry32);
CloseHandle(AhProcess);
end;
finally
CloseHandle(AHandle);
end;
end;

Process ID, Process handle, Window handle的更多相关文章

  1. Transaction (Process ID xxx) was deadlocked on lock

    Transaction (Process ID 161) was deadlocked on lock | communication buffer resources with another pr ...

  2. 多线程处理sql server2008出现Transaction (Process ID) was deadlocked on lock resources with another process and has been chose问题

    多线程处理sql server2008某个表中的数据时,在Update记录的时候出现了[Transaction (Process ID 146) was deadlocked on lock reso ...

  3. java代码中获取进程process id(转)

    另一方面,线程ID=进程ID+内部线程对象ID并不成立,    参考: blog.csdn.net/heyetina/article/details/6633901     如何在java代码中获取进 ...

  4. check process id exists

    kill -0 pid sending the signal 0 to a given PID just checks if any process with the given PID is run ...

  5. 进程ID[PID(Process ID)]与端口号[(Port ID)]的联系

    1.首先声明一点:PID不是端口(port id),而是Process ID进程号的意思. 2.那么,什么是进程号? 采集网友的意见就是: 进程号,是系统分配给么一个进程的唯一标识符.PID就是各进程 ...

  6. 查看进程id, 父进程id _How do I get the parent process ID of a given child process?

    How to get parent pid from a given children pid? I know I can mannully check it under /proc, I am wo ...

  7. open数据库报错ERROR at line 1: ORA-03113: end-of-file on communication channel Process ID: 3880 Session ID: 125 Serial number: 3

    1.今天打开数据时,失败,报错 ERROR at line 1:ORA-03113: end-of-file on communication channelProcess ID: 3880Sessi ...

  8. [Java][Android][Process] 分享 Process 运行命令行封装类型

    我在以前的文章中提到,使用Java不会有一个问题,创建运行命令来创建太多进程后创建进程行语句. [Android] ProcessBuilder与Runtime.getRuntime().exec分别 ...

  9. linux 终端报错 Out of memory: Kill process[PID] [process name] score问题分析

    从Out of memory来看是内存超出了,后面的 Kill process[PID] [process name] score好像和进程有关了,下面我们就一起来看看linux 终端报错 Out o ...

随机推荐

  1. Lempel-Ziv algorithm realization

    Lempel-Ziv 复杂度程序 随着人们对非线性方法的分析越加深入,他们发现,虽然关联维度和最大李雅谱诺夫指数在分析脑电时具有一定的帮助,但是它们对数据的依赖性太强,对干扰和噪 声太敏感,而且要得到 ...

  2. str.format() 格式化字符串函数

    语法 它通过{}和:来代替%. “映射”示例 通过位置 In [1]: '{0},{1}'.format('kzc',18) Out[1]: 'kzc,18' In [2]: '{},{}'.form ...

  3. GitBash、EGit、SourceTree三个Git管理工具对比

    Git管理工具对比(GitBash.EGit.SourceTree) GitBash是采用命令行的方式对版本进行管理,功能最为灵活强大,但是由于需要手动输入希望修改的文件名,所以相对繁琐. EGit是 ...

  4. 记点事! oracle 调用外部命令

    oracle执行系统命令   测试成功环境:windows XP+oracle 10g.window 2008 R2 + 11g   代码如下: www.2cto.com   Sql代码   crea ...

  5. inux命令英文缩写的含义(方便记忆) 2

    linux常用命令的英文单词缩写 命令缩写: ls:list(列出目录内容) cd:Change Directory(改变目录) su:switch user 切换用户rpm:redhat packa ...

  6. [笔记]Linux NTP命令 (ESX适用)

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://delxu.blog.51cto.com/975660/307513 [推荐阅读] ...

  7. webStorage,离线缓存

    一.webStorage 1.目标 1.了解cookie的不足之处,引入webstorage的概念    2.学习并且掌握webstorage有哪两种    3.学习并且掌握sessionStorag ...

  8. jmeter-----用户参数和用户定义变量的区别

    在调试脚本的时候,可以使用前置处理器中的用户参数组件进行数据的提供,在该数据中可以使用固定值也可以使用变量值. 如果是固定不变的一些配置项,不需要多个值的时候,也可以使用用户已定义的变量组件. 一.界 ...

  9. ssh连接远程主机免密登入

    核心思想: 1.本地主机生成公钥私钥,私钥自己存着,公钥传到远程主机.ssh文件夹下authorized_keys文件(默认是这个,用追加的方式) 2.本地连接远程主机,公私钥对上就可以免密登入了. ...

  10. [实战]MVC5+EF6+MySql企业网盘实战(14)——逻辑重构

    写在前面 上篇文章关于修改文件夹和文件名称导致的找不到物理文件的问题,这篇文章将对其进行逻辑的修改. 系列文章 [EF]vs15+ef6+mysql code first方式 [实战]MVC5+EF6 ...