我有一个批处理脚本,希望能够用快捷键运行,该脚本应该对活动窗口执行一些操作(例如创建特定的文件夹集合或将文件夹中所有文件名转换为小写字母)。因此,当调用脚本时,需要引用活动窗口。
我尝试将别名的“启动位置”字段留空,但是echoing %cd%总是打印出“C:\ Windows \ System32”,而不是当前活动窗口。
我尝试将别名的“启动位置”字段留空,但是echoing %cd%总是打印出“C:\ Windows \ System32”,而不是当前活动窗口。
通过调用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
@if (@a==@b) @end /* JScript multiline comment
:: begin batch portion
@echo off
setlocal
for /f "delims=" %%I in ('cscript /nologo /e:Jscript "%~f0"') do (
echo PID of this console window is %%I
)
goto :EOF
:: end batch portion / begin JScript */
var oShell = WSH.CreateObject('wscript.shell'),
johnConnor = oShell.Exec('%comspec% /k @echo;');
// returns PID of the direct child of explorer.exe
function getTopPID(PID, child) {
var proc = GetObject("winmgmts:Win32_Process=" + PID);
// uncomment the following line to watch the script walk up the ancestor tree
// WSH.Echo(proc.name + ' has a PID of ' + PID);
return (proc.name == 'explorer.exe') ? child : getTopPID(proc.ParentProcessID, PID);
}
var PID = getTopPID(johnConnor.ProcessID);
johnConnor.Terminate();
// send the console window to the back for a second, then refocus, just to show off
oShell.SendKeys('%{ESC}');
WSH.Sleep(1000);
oShell.AppActivate(PID);
// output PID of console window
WSH.Echo(PID);