如何在PowerShell脚本中调用SetCurrentProcessExplicitAppUserModelID方法
解决PowerShell中调用SetCurrentProcessExplicitAppUserModelID设置AUMID的问题
问题描述
我的Windows应用会启动另一个由PowerShell脚本编译而成的EXE程序,希望通过设置相同的AUMID让这两个EXE在任务栏中分组显示。现有一段调用shell32.dll的C#代码,我已编写了部分PowerShell代码,但不知如何正确调用SetCurrentProcessExplicitAppUserModelID方法。
参考C#代码
[DllImport("shell32.dll", SetLastError=true)] static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs(UnmanagedType.LPWStr)] string AppID); SetCurrentProcessExplicitAppUserModelID("MyAUMID");
已编写的PowerShell代码片段
$loadLibrary = @' [DllImport("shell32.dll", SetLastError=true)] static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs( UnmanagedType.LPWStr )] string AppID ); '@
完整解决方案
你需要通过Add-Type命令将定义的P/Invoke代码编译成.NET类型,之后就能调用其中的静态方法了。完整的PowerShell代码如下:
# 定义P/Invoke方法 $appUserModelIDDef = @' [DllImport("shell32.dll", SetLastError=true)] public static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs( UnmanagedType.LPWStr )] string AppID ); '@ # 将定义添加为.NET类型 Add-Type -MemberDefinition $appUserModelIDDef -Namespace Win32 -Name Shell32 # 调用方法设置AUMID [Win32.Shell32]::SetCurrentProcessExplicitAppUserModelID("MyAUMID")
关键说明
- 使用
Add-Type的-MemberDefinition参数传入P/Invoke代码,指定命名空间和类型名,方便后续调用 - 调用静态方法时,需要通过
[命名空间.类型名]::方法名()的格式执行 - 确保两个程序设置完全相同的AUMID字符串,这样任务栏才会将它们分组显示
内容的提问来源于stack exchange,提问作者Eric van Loon
相关产品推荐
相关产品推荐

