获取COM服务器的PID [英] Get PID of COM server

查看:469
本文介绍了获取COM服务器的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在powershell中创建一个com对象,如下:

I create a com object in powershell like so:

$application = new-object -ComObject "word.application"

是否有办法获取已启动的MS Word实例的PID(或某些其他唯一标识符) ?

Is there a way to get the PID (or some other unique identifier) of the launched MS Word instance?

我想检查程序是否被阻止,例如

I want to check if the program is blocked e.g. by modal dialogs asking for passwords, and I can't do it from whithin PowerShell.

推荐答案

好的,我找到了如何使用PowerShell做到这一点,我们需要调用Windows API。诀窍是获得HWND,这是暴露在Excel和Powerpoint,但不是在Word中。获取它的唯一方法是将应用程序窗口的名称更改为唯一的,并使用FindWindow找到它。然后,我们可以使用GetWindowThreadProcessId函数获取PID:

Ok, I found out how to do it, we need to call the Windows API. The trick is to get the HWND, which is exposed in Excel and Powerpoint, but not in Word. The only way to get it is to change the name of the application window to something unique and find it using "FindWindow". Then, we can get the PID using the "GetWindowThreadProcessId" function:

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

public static class Win32Api
{
[System.Runtime.InteropServices.DllImportAttribute( "User32.dll", EntryPoint =  "GetWindowThreadProcessId" )]
public static extern int GetWindowThreadProcessId ( [System.Runtime.InteropServices.InAttribute()] System.IntPtr hWnd, out int lpdwProcessId );

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}
"@


$application = new-object -ComObject "word.application"

# word does not expose its HWND, so get it this way
$caption = [guid]::NewGuid()
$application.Caption = $caption
$HWND = [Win32Api]::FindWindow( "OpusApp", $caption )

# print pid
$myPid = [IntPtr]::Zero
[Win32Api]::GetWindowThreadProcessId( $HWND, [ref] $myPid );
"PID=" + $myPid | write-host

这篇关于获取COM服务器的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆