如何在运行批处理脚本时获取当前活动窗口?

Jos*_*eti 4 windows powershell batch-file

我有一个我想用热键运行的批处理脚本,这个脚本应该在活动窗口中进行一些操作(例如,创建一组特定的文件夹,或小写文件夹中文件的所有名称).因此,脚本需要在调用时引用活动窗口.

我试图将别名的"开始"字段留空,但回显%cd%始终打印"C:\ Windows\System32"而不是当前活动窗口.

CB.*_*CB. 13

您可以使用user32.dll的pinvoke查找哪个进程将窗口置于前台.我在脚本中使用了这个技巧来处理system.window.forms.sendkeys方法:

Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class Tricks {
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
}
"@

$a = [tricks]::GetForegroundWindow()

get-process | ? { $_.mainwindowhandle -eq $a } # in my case:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------

    161       7    13984      15820    91     9,75   7720 Console
Run Code Online (Sandbox Code Playgroud)