Вопрос по – Как пакетный файл может запустить программу и установить положение и размер окна?

24

У меня есть пакетный файл, который устанавливает среду рабочего стола для меня, когда я пишу код. Файл называется:SetEnv.cmd и он открывает 3 других окна:

An instance of Windows Explorer that is set to the app server's deploy directory. A second instance of Windows Explorer that is set to the directory where my deployment file is written. A console window to start my application server.

Вот содержимоеSetEnv.cmd:

<code>Explorer /n,c:\develop\jboss-4.2.3.GA\server\default\deploy
Explorer /n,c:\develop\Project\Mapping\deploy
cmd /c SetupEnvCmd.cmd
</code>

А вот и содержаниеSetupEnvCmd.cmd:

<code>cd C:\develop\jboss-4.2.3.GA\bin
run
</code>

Каждый раз, когда я запускаю это, мне приходится тратить время на перестановку и изменение размеров окон. Я не хочу, чтобы окна были свернутыми, потому что я много раз взаимодействую с каждым окном во время написания и тестирования кода. Есть ли способ, которым я могу контролировать положение и / или размер окон, которые открываются из скрипта?

Ваш Ответ

6   ответов
2

которые не хотят загружать сторонние инструменты и имеют современныеPowerShell (PS).

Сценарий был основан насообщение Гарри Галлер. Все папки из вопроса, но вы можете заменить на свои.

Создать файлSetPositionAndSizeForExplorerWindow.ps1 со сценарием PS:

# PowerShell script for opening Explorer windows and changing its position and size

# add .NET type
Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class Win32 {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string ClassName, IntPtr  TitleApp);
  }
  public struct RECT
  {
    public int Left;        // x position of upper-left corner
    public int Top;         // y position of upper-left corner
    public int Right;       // x position of lower-right corner
    public int Bottom;      // y position of lower-right corner
  }
"@

# set variable for RECT object
$rcWindow = New-Object RECT

#----- REPLACE WITH YOUR PATHs from HERE---------

# open first folder in separate Explorer process
explorer.exe "c:\develop\jboss-4.2.3.GA\server\default\deploy"

# magic sleep =) to wait starting explorer on slow machines
sleep -Milliseconds 1500

$h1 = (Get-Process | where {$_.mainWindowTitle -match "deploy"}).MainWindowHandle

# check if there is a window with this Title, if NO - return
if ($h1 -eq [IntPtr]::Zero) {return "Cannot find window with this Title"}

# bind RECT object with our window
[void][Win32]::GetWindowRect($h1,[ref]$rcWindow)
# set new position and size for window 
[void][Win32]::MoveWindow($h1, 10, 10, 700, 345, $true)

# remember PID to exclude it for next window with the same name
$duplicate = (Get-Process | where {$_.mainWindowTitle -match "deploy"}).Id

# open second folder in separate Explorer process
explorer.exe "c:\develop\Project\Mapping\deploy"
sleep -Milliseconds 1500
$h1 = (Get-Process | where {$_.mainWindowTitle -match "deploy" -and $_.Id -ne $duplicate}).MainWindowHandle
if ($h1 -eq [IntPtr]::Zero) {return "Cannot find window with this Title"}
[void][Win32]::GetWindowRect($h1,[ref]$rcWindow)
[void][Win32]::MoveWindow($h1, 400, 20, 700, 335, $true)

# open cmd window with title SetupEnvCmd.cmd
cmd /c "start C:\develop\jboss-4.2.3.GA\bin\SetupEnvCmd.cmd"
sleep -Milliseconds 1500
# cmd.exe process has no own title, that's why we get PID searching by CommandLine process property
$process = "cmd.exe"
$cmdPID = Get-CimInstance Win32_Process -Filter "name = '$process'" | where {$_.CommandLine -match "SetupEnvCmd"} | select ProcessId
$h1 = (Get-Process | where {$_.Id -eq $cmdPID.ProcessId}).MainWindowHandle
if ($h1 -eq [IntPtr]::Zero) {return "Cannot find window with this Title"}
[void][Win32]::GetWindowRect($h1,[ref]$rcWindow)
[void][Win32]::MoveWindow($h1, 200, 400, 800, 400, $true)

Переместить его вC:\develop folder. Create OpenDevelopEnv.bat файл для запуска этого скрипта .ps1 (чтобы не вникать в политику безопасности PS):

Powershell -executionpolicy RemoteSigned -File "C:\develop\SetPositionAndSizeForExplorerWindow.ps1"

БежатьOpenDevelopEnv.bat

For multi-display configuration Вы можете использовать отрицательные координаты, например: для открытия окна на левом дисплее (относительно основного) вы можете написать:

[void][Win32]::MoveWindow($h1, -600, 400, 800, 400, $true)

Disadvantages:

PowerShell must be installed; required windows must be closed; folders starts in separate processes; using of sleep time for correct work on slow machines.

Tested on: Windows 10 Pro 1803 x64 / x86 с PSVersion 5.1 (администратор и обычные пользователи)

4

t) через командный файл. Если ваш VBS выглядит так:

'FILENAME: SetEnv.vbs
Set Shell = WScript.CreateObject("WScript.Shell")
Shell.Run "Explorer /n,c:\develop\jboss-4.2.3.GA\server\default\deploy", 4, False
Shell.Run "Explorer /n,c:\develop\Project\Mapping\deploy", 4, False

4 означает запустить окно в его самом последнем размере / позиции.False означает, что он не будет ждать возврата к выполнению следующей строки вашего сценария. К сожалению, это не дает вам полного контроля над вашим точным размером / позиционированием окна, но оно должно помнить последний размер / позиционирование.

Больше информации здесь:http://www.devguru.com/Technologies/wsh/quickref/wshshell_Run.html

Таким образом, ваш новый SetEnv.cmd может быть:

@echo off
REM note there's a difference between cscript and wscript
REM wscript is usually the default launcher
cscript SetEnv.vbs
cd C:\develop\jboss-4.2.3.GA\bin
run
Error: User Rate Limit ExceededShellError: User Rate Limit Exceeded Sean Mickey
Error: User Rate Limit ExceededExplorerError: User Rate Limit Exceeded
0

StartX, Я не использовал его, но похоже, что вы можете использовать его для запуска приложения с определенной позицией и размером.

StartX, a very simple utility to allow you to call the CreateProcess API from the command line.

Некоторые из его параметров командной строки:

StartX ["title"] [/Dpath] [/MIN] [/MAX] [/Px,y] [/Scx1,cy1]

x,y: Specifies the x and y offset, in pixels, of the upper left corner of a window if a new window is created. The offset is from the upper left corner of the screen.

cx1, cy2: Specifies the width and height, in pixels, of the window if a new window is created.

17

Вот альтернативный способ с утилитой nircmd изhttp://www.nirsoft.net/utils/nircmd.html
Примеры:

nircmd win move ititle "cmd.exe" 5 5 10 10
nircmd win setsize ititle "cmd.exe" 30 30 100 200
nircmd cmdwait 1000 win setsize ititle "cmd.exe" 30 30 1000 600

Вот содержимое SetEnv.cmd:

    Explorer /n,c:\develop\jboss-4.2.3.GA\server\default\deploy
    nircmd wait 1000 win setsize ititle "something" x, y, width, height
    Explorer /n,c:\develop\Project\Mapping\deploy
    nircmd wait 1000 win setsize ititle "something" x, y, width, height

Где x, y верхний левый угол, расположение и ширина, высота - размер окна & Quot; кое & Quot; заголовок окна обычно имя папки, например. & Quot; C: \ разработки \ \ jboss-4.2.3.GA сервер по умолчанию \ \ развернуть & Quot; & Quot; ждать & quot; возможно, потребуется скорректировать, чтобы дать время для инициализации окна приложения. Таким образом, вы бы увеличили время, если у вас есть антивирусные сканеры, которые задерживают. Не столько проблема с explorer.exe или cmd.exe, но что-то вроде приложений Firefox или java может варьироваться от нескольких секунд до нескольких десятков секунд в зависимости от скорости вашего оборудования и настройки ОС. Вы также можете настроить окно cmd.exe или & quot; запустить & quot; приложением, добавив строки в «SetupEnvCmd.cmd», предполагая «выполнить» является асинхронным приложением win32, в противном случае добавьте & quot; start & quot; команда.

-1

AutoHotKey, который легко справится с этим (лучше, чем Powershell и Batch, на мой взгляд).

В качестве простого примера, чтобы запустить два экземпляра Explorer, измените их размер (и переместите), затем сделайте то же самое с окном cmd, вы можете сделать что-то вроде этого:

Run Explorer /n,c:\develop\jboss-4.2.3.GA\server\default\deploy
Run Explorer /n,c:\develop\Project\Mapping\deploy
WinMove, deploy, server\default, 0, 0, 200, 200
WinMove, deploy, Project\Mapping, 200, 0, 200, 200
Run cmd /c SetupEnvCmd.cmd
WinMove, C:\develop\jboss-4.2.3.GA\bin, 0, 200

Справочный документ WinMove

13

грамм и командного файла.
У меня есть два решения; один для компьютера с одним монитором, а другой для компьютера с несколькими мониторами.

SOLUTION 1 : FOR SINGLE MONITOR COMPUTER

Этот демонстрационный пакетный файл откроет два окна проводника бок о бок и по центру экрана на основном мониторе.
Прочитайте описание в командном файле.

Используемые инструменты:
1. MonitorInfoView Нир Софер(41 KB) ...........домашняя страница
2. NirCmd Нир Софер(43 KB) ............................домашняя страница
3. A batch file (6 KB) ............................................увидеть ниже

Соберите все три файла в каталог.
Это командный файл, готовый для запуска в любой системе Windows(run it for an instant demo):

@echo off
REM ----- GIVE THIS CONSOLE WINDOW TITLE A UNIQUE STRING ID
title OPEN-2-EXPLORER-WINDOWS-SIDE-BY-SIDE-AND-CENTERED-ON-SCREEN-AT-THE-PRIMARY-MONITOR___20131209084355
pushd %~dp0

REM ----- HIDE THIS CONSOLE WINDOW (HOOKS THE WINDOW TITLE)
nircmd.exe win hide ititle "OPEN-2-EXPLORER-WINDOWS-SIDE-BY-SIDE-AND-CENTERED-ON-SCREEN-AT-THE-PRIMARY-MONITOR___20131209084355"

REM ********************** DESCRIPTION ************************************
REM ** This script opens one or more windows with specified screen properties
REM ** at the primary monitor (containing the taskbar). The "X/Y position" and
REM ** "W/H size" of the windows are auto-set by this script and the monitor
REM ** resolution is auto-calculated to suit.
REM ** 'MonitorInfoView.exe' is the helper tool used to capture the resolution
REM ** info of the monitor. 
REM ** 'nircmd.exe' is the tool performing all the display trickery.
REM **
REM ** To tweak this script, go to the code section named:
REM ** >>>>> USER INPUT/PREFERENCES ARE ALL SET HERE <<<<<
REM ***********************************************************************

REM ----- CLEAR ANY PREVIOUS JOB OUTPUTS IF THEY EXIST
if exist ~TMP.TXT type NUL > ~TMP.TXT

REM ----- OUTPUT THE PRIMARY MONITOR INFORMATION TO A TEXT FILE
MonitorInfoView.exe /hideinactivemonitors 1 /stext ~TMP.TXT

REM ----- ISOLATE THE RESOLUTION LINE, REMOVING ALL THE OTHER LINES IN THE TEXT FILE
for /f "delims=" %%A in ('type "~TMP.TXT" ^|find.exe /i "Maximum Resolution"') do echo %%A>~TMP.TXT

REM ----- GET THE RESOLUTION NUMBERS, AND SET THEM AS VARIABLES
for /f "tokens=3,4 delims=:X " %%A in ('type "~TMP.TXT"') do set _SCREENW_=%%A& set _SCREENH_=%%B


REM >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
REM >>>>>>>>>> USER INPUT/PREFERENCES ARE ALL SET HERE [BEGIN] <<<<<<<<<<<<

REM ----- LEFT WINDOW PROPERTIES

    set _WINLEFT_=%SYSTEMDRIVE%
    set /a _WINLEFTW_=(%_SCREENW_% / 3) + 50
    set /a _WINLEFTH_=(%_SCREENH_% / 2) + 200
    set /a _WINLEFTX_=(%_SCREENW_% - %_WINLEFTW_%) / 5
    set /a _WINLEFTY_=(%_SCREENH_% - %_WINLEFTH_%) / 2

REM ----- RIGHT WINDOW PROPERTIES

    set _WINRIGHT_=%USERPROFILE%
    set /a _WINRIGHTW_=(%_SCREENW_% / 3) + 50
    set /a _WINRIGHTH_=(%_SCREENH_% / 2) + 200
    set /a _WINRIGHTX_=(%_WINLEFTX_%) + (%_WINLEFTW_%)
    set /a _WINRIGHTY_=(%_SCREENH_% - %_WINRIGHTH_%) / 2

REM ----- ADJUST THE WAIT TIME (MILLISECONDS) BETWEEN EACH WINDOW LAUNCH.
REM ----- IF TOO QUICK, THE FOLLOWING WINDOW WILL NOT SET IN THE CORRECT SCREEN POSITION.
REM ----- | FOR FAST SYSTEM: TRY 200 | NORMAL SYSTEM: TRY 400-600 | BLOATED SYSTEM: TRY 800-1200+

    set _WAITTIME_=400

REM ----- ON WINDOWS NT5 (XP, 2000), RUNNING EXPLORER WITH THE 'N' SWITCH WOULD RELIABLY GIVE
REM ----- YOU 1-PANE VIEW (HIDDEN LEFT NAV PANE). ALSO, SHOWING/HIDING OF THE LEFT NAV PANE WAS
REM ----- INSTANTLY TOGGLED BY AN ICON ON THE EXPLORER GUI TOOLBAR.
REM ----- ON WINDOWS NT6 (VISTA, 7), EXPLORER WILL NOT OBEY YOUR COMMANDS AT ALL TIMES AND IT
REM ----- IS A "PITA" TO CONTROL THE GRAPHIC USER INTERFACE. 
REM ----- THIS INPUT SECTION IS A WORKAROUND TO FORCE AN INSTANCE OF NT6 EXPLORER TO BE
REM ----- TOGGLED TO A SPECIFIED VIEW.
REM ----- |
REM ----- | INSERT ONE OF THESE VALUES INTO THE VARIABLE _EXPLORER_VIEW_MYPREF_
REM ----- | | FOR EXPLORER 2-PANE VIEW (SHOW LEFT NAVPANE):  150100000100000000000000E5010000
REM ----- | | FOR EXPLORER 1-PANE VIEW (HIDE LEFT NAVPANE):  1501000000000000000000007B020000

    set _EXPLORER_VIEW_MYPREF_=1501000000000000000000007B020000

REM >>>>>>>>>> USER INPUT/PREFERENCES ARE ALL SET HERE [END] <<<<<<<<<<<<<<
REM >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


REM ----- RUN THE TASK . . .

REM ----- REGKEY 'HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Modules' DOES NOT EXIST IN NT5 OR EARLIER
REM ----- BUT TO ELIMINATE DOUBT WE WILL PERFORM A CONDITIONAL VERSION CHECK
for /f "tokens=2 delims=[]" %%A in ('ver') do set _THIS_OS_VERSTRING_=%%A
set _THIS_OS_VERSTRING_=%_THIS_OS_VERSTRING_:Version =%
for /f "tokens=1,2,3* delims=." %%A in ("%_THIS_OS_VERSTRING_%") do set _THIS_OS_MAJORVERSION_=%%A
if %_THIS_OS_MAJORVERSION_% leq 5 goto SKIP1

set _EXPLORER_VIEW_REGKEY_=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Modules\GlobalSettings\Sizer
set _EXPLORER_VIEW_REGVAL_=PageSpaceControlSizer
if exist ~TMP.TXT type NUL > ~TMP.TXT
reg.exe query %_EXPLORER_VIEW_REGKEY_% > ~TMP.TXT
if %ERRORLEVEL% equ 1 goto SKIP1
for /f "delims=" %%A in ('type "~TMP.TXT" ^|find.exe /i "%_EXPLORER_VIEW_REGVAL_%"') do echo %%A>~TMP.TXT
for /f "tokens=1-3 delims= " %%A in ('type "~TMP.TXT"') do set _EXPLORER_VIEW_SYSTEMPREF_=%%C
reg.exe add %_EXPLORER_VIEW_REGKEY_% /v %_EXPLORER_VIEW_REGVAL_% /t REG_BINARY /d %_EXPLORER_VIEW_MYPREF_% /f 2>nul >nul
nircmd.exe wait %_WAITTIME_%

:SKIP1
nircmd.exe exec show "explorer.exe" /n,%_WINLEFT_%
nircmd.exe wait %_WAITTIME_%
nircmd.exe win setsize foreground %_WINLEFTX_% %_WINLEFTY_% %_WINLEFTW_% %_WINLEFTH_%
nircmd.exe wait %_WAITTIME_%
nircmd.exe exec show "explorer.exe" /n,%_WINRIGHT_%
nircmd.exe wait %_WAITTIME_%
nircmd.exe win setsize foreground %_WINRIGHTX_% %_WINRIGHTY_% %_WINRIGHTW_% %_WINRIGHTH_%

REM ----- RESET SYSTEM PREF, CLEAR MEMORY, CLEANUP, QUIT . . .

find.exe /i /c "%_EXPLORER_VIEW_REGVAL_%" ~TMP.TXT
if %ERRORLEVEL% equ 1 goto SKIP2
nircmd.exe wait %_WAITTIME_%
nircmd.exe wait %_WAITTIME_%
reg.exe add %_EXPLORER_VIEW_REGKEY_% /v %_EXPLORER_VIEW_REGVAL_% /t REG_BINARY /d %_EXPLORER_VIEW_SYSTEMPREF_% /f 2>nul >nul
:SKIP2
set _SCREENW_=
set _SCREENH_=
set _WINLEFTX_=
set _WINLEFTY_=
set _WINLEFTW_=
set _WINLEFTH_=
set _WINRIGHTX_=
set _WINRIGHTY_=
set _WINRIGHTW_=
set _WINRIGHTH_=
set _WAITTIME_=
set _THIS_OS_VERSTRING_=
set _THIS_OS_MAJORVERSION_=
set _EXPLORER_VIEW_REGKEY_=
set _EXPLORER_VIEW_REGVAL_=
set _EXPLORER_VIEW_MYPREF_=
set _EXPLORER_VIEW_SYSTEMPREF_=
del /f /q ~TMP.TXT
popd
exit



SOLUTION 2 : FOR MULTI-MONITOR COMPUTER

Этот демонстрационный пакетный файл откроет два окна проводника рядом друг с другом и по центру экрана на другом (не основном) мониторе рабочего стола с двумя мониторами. Прочитайте описание в командном файле.

Note: For this demo, I am assuming the left monitor is Monitor-1 (the primary active monitor, containing the taskbar) and right monitor is Monitor-2 (the non-primary active monitor). If your setup is different, then tweak the script.

Используемые инструменты:
1. MonitorInfoView Нир Софер(41 KB) ..............домашняя страница
2. MultiMonitorTool Нир Софер(102 KB) ...........домашняя страница
3. NirCmd Нир Софер(43 KB) ...............................домашняя страница
4. A batch file (6 KB) ...............................................увидеть ниже

Соберите все четыре файла в каталог.
Это командный файл, готовый для запуска в любой системе Windows (run it for an instant demo):

@echo off
REM ----- GIVE THIS CONSOLE WINDOW TITLE A UNIQUE STRING ID
title OPEN-2-EXPLORER-WINDOWS-SIDE-BY-SIDE-AND-CENTERED-ON-SCREEN-AT-MONITOR-2-OF-A-MULTI-MONITOR-DESKTOP___20140101024519
pushd %~dp0

REM ----- HIDE THIS CONSOLE WINDOW (HOOKS THE WINDOW TITLE)
nircmd.exe win hide ititle "OPEN-2-EXPLORER-WINDOWS-SIDE-BY-SIDE-AND-CENTERED-ON-SCREEN-AT-MONITOR-2-OF-A-MULTI-MONITOR-DESKTOP___20140101024519"

REM ********************** DESCRIPTION ************************************
REM ** This script opens one or more windows with specified screen properties
REM ** at a chosen monitor of a multi-monitor desktop. The "X/Y position" and
REM ** "W/H size" of the windows are auto-set by this script and the monitor
REM ** resolutions are auto-calculated to suit. 
REM ** 'MonitorInfoView.exe' is the helper tool used to isolate the resolution
REM ** info of the primary monitor (containing the taskbar).
REM ** 'MultiMonitorTool.exe' is the helper tool used to capture the 
REM ** resolution info of all monitors and for isolating the resolution info
REM ** of the other (non-primary) monitor.
REM ** 'nircmd.exe' is the tool performing all the display trickery.
REM **
REM ** To tweak this script, go to the code section named:
REM ** >>>>> USER INPUT/PREFERENCES ARE ALL SET HERE <<<<<
REM ***********************************************************************

REM ----- CLEAR ANY PREVIOUS JOB OUTPUTS IF THEY EXIST
if exist ~TMP.TXT type NUL > ~TMP.TXT
if exist ~TMP2.TXT type NUL > ~TMP2.TXT

REM ----- OUTPUT THE PRIMARY MONITOR (MONITOR-1) INFORMATION TO A TEXT FILE
MonitorInfoView.exe /hideinactivemonitors 1 /stext ~TMP.TXT

REM ----- ISOLATE THE RESOLUTION LINE OF MONITOR-1, REMOVING ALL THE OTHER LINES IN THE TEXT FILE
for /f "delims=" %%A in ('type "~TMP.TXT" ^|find.exe /i "Maximum Resolution"') do echo %%A>~TMP.TXT

REM ----- GET THE RESOLUTION NUMBERS OF MONITOR-1, AND SET THEM AS VARIABLES
for /f "tokens=3,4 delims=:X " %%A in ('type "~TMP.TXT"') do (
set _M1_SCREENW_=%%A
set _M1_SCREENH_=%%B
)

REM ----- OUTPUT INFO OF ALL MONITORS TO TEXT FILE
MultiMonitorTool.exe /stext ~TMP.TXT

REM ----- TRY REMOVING MONITOR-1 RESOLUTION LINE (KEEPING MONITOR-2 RESOLUTION LINE)
find.exe /i /v "%_M1_SCREENW_% X %_M1_SCREENH_%" < ~TMP.TXT > ~TMP2.TXT

REM ----- TRY ISOLATING MONITOR-2 RESOLUTION LINE (REMOVING ALL THE OTHER LINES IN THE TEXT FILE)
for /f "delims=" %%A in ('type "~TMP2.TXT" ^|find.exe /i "Maximum Resolution"') do echo %%A>~TMP2.TXT

REM ----- CONDITIONALLY GET THE RESOLUTION NUMBERS OF MONITOR-2, AND SET THEM AS VARIABLES ...
REM ----- CASE(A): IF MONITORS HAVE SAME RESOLUTION, ASSUME NO LINES HAVE STRING "Maximum Resolution". 
REM ----- CASE(B): IF MONITORS HAVE DIFFERENT RESOLUTION, ASSUME ONE LINE HAS STRING "Maximum Resolution".
find.exe /i /c "Maximum Resolution" ~TMP2.TXT
if %ERRORLEVEL% equ 1 (
set _M2_SCREENW_=%_M1_SCREENW_%&set _M2_SCREENH_=%_M1_SCREENH_%
) else (
for /f "tokens=3,4 delims=:X " %%A in ('type "~TMP2.TXT"') do set _M2_SCREENW_=%%A&set _M2_SCREENH_=%%B
)    


REM >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
REM >>>>>>>>>> USER INPUT/PREFERENCES ARE ALL SET HERE [BEGIN] <<<<<<<<<<<<

REM ----- MONITOR-2 LEFT WINDOW PROPERTIES

    set _M2_WINLEFT_=%SYSTEMDRIVE%
    set /a _M2_WINLEFTW_=(%_M2_SCREENW_% / 3) + 50
    set /a _M2_WINLEFTH_=(%_M2_SCREENH_% / 2) + 200
    set /a _M2_WINLEFTX_=(%_M1_SCREENW_%) + (%_M2_SCREENW_% - %_M2_WINLEFTW_%) / 5
    set /a _M2_WINLEFTY_=(%_M2_SCREENH_% - %_M2_WINLEFTH_%) / 2

REM ----- MONITOR-2 RIGHT WINDOW PROPERTIES

    set _M2_WINRIGHT_=%USERPROFILE%
    set /a _M2_WINRIGHTW_=(%_M2_SCREENW_% / 3) + 50
    set /a _M2_WINRIGHTH_=(%_M2_SCREENH_% / 2) + 200
    set /a _M2_WINRIGHTX_=(%_M2_WINLEFTX_%) + (%_M2_WINLEFTW_%)
    set /a _M2_WINRIGHTY_=(%_M2_SCREENH_% - %_M2_WINRIGHTH_%) / 2

REM ----- ADJUST THE WAIT TIME (MILLISECONDS) BETWEEN EACH WINDOW LAUNCH.
REM ----- IF TOO QUICK, THE FOLLOWING WINDOW WILL NOT SET IN THE CORRECT SCREEN POSITION.
REM ----- | FOR FAST SYSTEM: TRY 200 | NORMAL SYSTEM: TRY 400-600 | BLOATED SYSTEM: TRY 800-1200+

    set _WAITTIME_=400

REM ----- ON WINDOWS NT5 (XP, 2000), RUNNING EXPLORER WITH THE 'N' SWITCH WOULD RELIABLY GIVE
REM ----- YOU 1-PANE VIEW (HIDDEN LEFT NAV PANE). ALSO, SHOWING/HIDING OF THE LEFT NAV PANE WAS
REM ----- INSTANTLY TOGGLED BY AN ICON ON THE EXPLORER GUI TOOLBAR.
REM ----- ON WINDOWS NT6 (VISTA, 7), EXPLORER WILL NOT OBEY YOUR COMMANDS AT ALL TIMES AND IT
REM ----- IS A "PITA" TO CONTROL THE GRAPHIC USER INTERFACE. 
REM ----- THIS INPUT SECTION IS A WORKAROUND TO FORCE AN INSTANCE OF NT6 EXPLORER TO BE
REM ----- TOGGLED TO A SPECIFIED VIEW.
REM ----- |
REM ----- | INSERT ONE OF THESE VALUES INTO THE VARIABLE _EXPLORER_VIEW_MYPREF_
REM ----- | | FOR EXPLORER 2-PANE VIEW (SHOW LEFT NAVPANE):  150100000100000000000000E5010000
REM ----- | | FOR EXPLORER 1-PANE VIEW (HIDE LEFT NAVPANE):  1501000000000000000000007B020000

    set _EXPLORER_VIEW_MYPREF_=1501000000000000000000007B0,20000

REM >>>>>>>>>> USER INPUT/PREFERENCES ARE ALL SET HERE [END] <<<<<<<<<<<<<<
REM >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


REM ----- RUN THE TASK . . .

REM ----- REGKEY 'HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Modules' DOES NOT EXIST IN NT5 OR EARLIER
REM ----- BUT TO ELIMINATE DOUBT WE WILL PERFORM A CONDITIONAL VERSION CHECK
for /f "tokens=2 delims=[]" %%A in ('ver') do set _THIS_OS_VERSTRING_=%%A
set _THIS_OS_VERSTRING_=%_THIS_OS_VERSTRING_:Version =%
for /f "tokens=1,2,3* delims=." %%A in ("%_THIS_OS_VERSTRING_%") do set _THIS_OS_MAJORVERSION_=%%A
if %_THIS_OS_MAJORVERSION_% leq 5 goto SKIP1

set _EXPLORER_VIEW_REGKEY_=HKEY_CURRENT_USER\Software\M,icrosoft\Windows\CurrentVersion\Explorer\Modules\GlobalSettings\Sizer
set _EXPLORER_VIEW_REGVAL_=PageSpaceControlSizer
if exist ~TMP.TXT type NUL > ~TMP.TXT
reg.exe query %_EXPLORER_VIEW_REGKEY_% > ~TMP.TXT
if %ERRORLEVEL% equ 1 goto SKIP1
for /f "delims=" %%A in ('type "~TMP.TXT" ^|find.exe /i "%_EXPLORER_VIEW_REGVAL_%"') do echo %%A>~TMP.TXT
for /f "tokens=1-3 delims= " %%A in ('type "~TMP.TXT"') do set _EXPLORER_VIEW_SYSTEMPREF_=%%C
reg.exe add %_EXPLORER_VIEW_REGKEY_% /v %_EXPLORER_VIEW_REGVAL_% /t REG_BINARY /d %_EXPLORER_VIEW_MYPREF_% /f 2>nul >nul
nircmd.exe wait %_WAITTIME_%

:SKIP1
nircmd.exe exec show "explorer.exe" /n,%_M2_WINLEFT_%
nircmd.exe wait %_WAITTIME_%
nircmd.exe win setsize foreground %_M2_WINLEFTX_% %_M2_WINLEFTY_% %_M2_WINLEFTW_% %_M2_WINLEFTH_%
nircmd.exe wait %_WAITTIME_%
nircmd.exe exec show "explorer.exe" /n,%_M2_WINRIGHT_%
nircmd.exe wait %_WAITTIME_%
nircmd.exe win setsize foreground %_M2_WINRIGHTX_% %_M2_WINRIGHTY_% %_M2_WINRIGHTW_% %_M2_WINRIGHTH_%


REM ----- RESET SYSTEM PREF, CLEAR MEMORY, CLEANUP, QUIT . . .

find.exe /i /c "%_EXPLORER_VIEW_REGVAL_%" ~TMP.TXT
if %ERRORLEVEL% equ 1 goto SKIP2
nircmd.exe wait %_WAITTIME_%
nircmd.exe wait %_WAITTIME_%
reg.exe add %_EXPLORER_VIEW_REGKEY_% /v %_EXPLORER_VIEW_REGVAL_% /t REG_BINARY /d %_EXPLORER_VIEW_SYSTEMPREF_% /f 2>nul >nul
:SKIP2
set _M1_SCREENW_=
set _M1_SCREENH_=
set _M2_SCREENW_=
set _M2_SCREENH_=
set _M2_WINLEFT_=
set _M2_WINLEFTX_=
set _M2_WINLEFTY_=
set _M2_WINLEFTW_=
set _M2_WINLEFTH_=
set _M2_WINRIGHT_=
set _M2_WINRIGHTX_=
set _M2_WINRIGHTY_=
set _M2_WINRIGHTW_=
set _M2_WINRIGHTH_=
set _WAITTIME_=
set _THIS_OS_VERSTRING_=
set _THIS_OS_MAJORVERSION_=
set _EXPLORER_VIEW_REGKEY_=
set _EXPLORER_VIEW_REGVAL_=
set _EXPLORER_VIEW_MYPREF_=
set _EXPLORER_VIEW_SYSTEMPREF_=
del /f /q ~TMP.TXT
del /f /q ~TMP2.TXT
popd
exit



More . . .
Run a command-line program and set the position/size of its console window

This demo batch file запустит программу командной строки и установит положение и размер ее окна консоли командной строки. Общая тема этого пакета такая же, как и в предыдущих двух решениях, но были некоторые уникальные проблемы и обходные пути, чтобы сделать эту работу ---- это окно командной строки, размещенное в & amp; CMD.EXE & apos; а не окно с графическим интерфейсом, например «EXPLORER.EXE» ---- Прочитайте все комментарии в командном файле для получения дополнительной информации. Прочитайте описание тоже.

Используемые инструменты:
1. MonitorInfoView Нир Софер(41 KB) ........домашняя страница
2. NirCmd Нир Софер(43 KB) .........................домашняя страница
3. GetPIDs Даниэль Шейбли(280 KB) ..............домашняя страница
4. A command-line program ......................... для этой демонстрации я использую UPX.EXE & apos; из того же каталога, что и пакет ...домашняя страница
5. A batch file (6 KB) .........................................увидеть ниже

Соберите все пять файлов в каталог.
Это командный файл, готовый для запуска в любой системе Windows(run it for an instant demo):

То, что собирается сделать этот демонстрационный пакет, кроме предоставления вам собственного окна консоли, это то, что он будет работатьupx.exe с переключателем командной строки--best -v -o getpids-compressed.exe getpids.exe , Мы собираемся сжать наш инструментGetPIDs (что составляет 280 КБ) до 88 КБ! .......... после запуска дважды щелкните строку заголовка этого окна консоли, чтобы увидеть интересное явление; это окно консоли ведет себя как графический интерфейс!

@echo off
setlocal enabledelayedexpansion enableextensions
pushd %~dp0%

REM ----- ADD SOME USEFUL INFORMATION TO THIS CONSOLE WINDOW TITLE.
for /f "tokens=3" %%A in ('getpids.exe') do set _PROCESS_ID_=%%A
title This batch file runs a command-line program and sets the position and size of its console window        (PROCESS ID = %_PROCESS_ID_%)

REM ********************** DESCRIPTION ************************************
REM ** This script opens a command-line program console window with specified
REM ** screen properties at the primary monitor (containing the taskbar).
REM ** The "X/Y position" and "W/H size" of the console window is auto-set by
REM ** this script and the monitor resolution is auto-calculated to suit.
REM ** 'MonitorInfoView.exe' is the helper tool used to capture the resolution
REM ** info of the monitor.
REM ** 'nircmd.exe' is the tool performing all the display trickery.
REM ** 'getpids.exe' is the helper tool used to capture the Process ID of the
REM ** working batch file, thus allowing us to identify which CMD.EXE host this
REM ** console window belongs to when looking at Task Manager.
REM **
REM ** To tweak this script, go to the code section named:
REM ** >>>>> USER INPUT/PREFERENCES ARE ALL SET HERE <<<<<
REM ***********************************************************************

REM ----- CLEAR ANY PREVIOUS JOB OUTPUTS IF THEY EXIST
if exist ~TMP.TXT type NUL > ~TMP.TXT

REM ----- OUTPUT THE PRIMARY MONITOR INFORMATION TO A TEXT FILE
MonitorInfoView.exe /hideinactivemonitors 1 /stext ~TMP.TXT

REM ----- ISOLATE THE RESOLUTION LINE, REMOVING ALL THE OTHER LINES IN THE TEXT FILE
for /f "delims=" %%A in ('type "~TMP.TXT" ^|find.exe /i "Maximum Resolution"') do echo %%A>~TMP.TXT

REM ----- GET THE RESOLUTION NUMBERS, AND SET THEM AS VARIABLES
for /f "tokens=3,4 delims=:X " %%A in ('type "~TMP.TXT"') do set _SCREENW_=%%A& set _SCREENH_=%%B


REM >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
REM >>>>>>>>>> USER INPUT/PREFERENCES ARE ALL SET HERE [BEGIN] <<<<<<<<<<<<

REM ----- ----------------------------------------
REM ----- |COMMAND-LINE PROGRAM TO BE RUN:  FILE NAME (WITH EXTENSION)
REM ----- |
REM ----- | |IF PROG TO BE RUN IS 'CMD.EXE' (WINDOWS COMMAND PROCESSOR)
REM ----- | |ALSO READ THE NEXT COMMENTS ABOUT SETTING SWITCHES

    set _MYPROGRAM_=upx.exe

REM ----- ----------------------------------------   
REM ----- |COMMAND-LINE PROGRAM TO BE RUN:  SWITCHES (TO BE PASSED TO THE PROGRAM)
REM ----- |
REM ----- | |YOU CAN LEAVE THIS VARIABLE WITH A BLANK VALUE IF RUNNING THE PROG WITHOUT ANY PARAMETERS
REM ----- | | 
REM ----- | | |IF THE VALUE CONTAINS THE CHARS  '|'  OR  '<'  OR  '>'  THIS BATCH WILL FAIL TO RUN !!!
REM ----- | | |
REM ----- | | | |YOU CAN APPEND EXTRA TEXT TO THE END OF THE COMMAND BY USING THE AMPERSAND CHARACTER '&'
REM ----- | | | | EXAMPLES:
REM ----- | | | | set _MYPROGRAMSWITCHES_=dir "%systemroot%\system32" /a/o/s/4 & this text will be ignored; useful for adding some inline comments.
REM ----- | | | | set _MYPROGRAMSWITCHES_=dir "%systemroot%\system32" /a/o/s/4         & this works too, and the extra blank spaces will also be ignored.
REM ----- | | | | 
REM ----- | | | | |IF PROG TO BE RUN IS 'CMD.EXE' (WINDOWS COMMAND PROCESSOR), PATH ARGUMENTS MUST POINT TO A SPECIFIC LOCATION
REM ----- | | | | |AND BE ABSOLUTE OR INCLUDE ENVIRONMENT VARIABLES, AND ALWAYS ENCLOSE PATHS IN QUOTES.
REM ----- | | | | | EXAMPLES:
REM ----- | | | | | set _MYPROGRAMSWITCHES_=type "C:\Folder With Spaces\File.txt"
REM ----- | | | | | set _MYPROGRAMSWITCHES_=type "C:\FolderWithoutSpaces\File.txt"
REM ----- | | | | | set _MYPROGRAMSWITCHES_=type "%SYSTEMROOT%\..\Folder With Spaces\File.txt"
REM ----- | | | | | set _MYPROGRAMSWITCHES_=type %0                                       <<<<<<<this batch file (quotes are optional; the only exception to the rule)
REM ----- | | | | | set _MYPROGRAMSWITCHES_=type "%~dp0%\..\File.txt"                     <<<<<<<goes back one Dir from this batch file
REM ----- | | | | | set _MYPROGRAMSWITCHES_=dir "%systemroot%\system32" /a/o/s/4          <<<<<<<displays directory listing of the System folder. NOTE: 'dir' by itself and
REM ----- | | | | |                                                                                without a specific path argument will resolve to the folder of this batch file.

    set _MYPROGRAMSWITCHES_=--best -v -o getpids-compressed.exe getpids.exe      &// original is 280 KB, will compress down to 88 KB

REM ----- ----------------------------------------
REM ----- |COMMAND-LINE PROGRAM TO BE RUN:  DIRECTORY PATH (OF THE PROGRAM)
REM ----- | 
REM ----- | |YOU CAN LEAVE THIS VARIABLE WITH A BLANK VALUE IF THE PROG IS AT SAME LOCATION AS BATCH
REM ----- | |THIS VARIABLE WILL BE IGNORED IF THE PROG IS 'CMD.EXE'
REM ----- | | 
REM ----- | | EXAMPLES:
REM ----- | | set _MYPROGRAMDIR_=.\                               <<<<<<<program and batch in same directory
REM ----- | |                                                                  dot backslash *OR* dot (trailing backslash is optional).
REM ----- | | set _MYPROGRAMDIR_=%dp0%                            <<<<<<<program and batch in same directory
REM ----- | |                                                                  same locatiion as previous but using environment variable.
REM ----- | | set _MYPROGRAMDIR_=..\                              <<<<<<<program is back one directory from batch
REM ----- | |                                                                  dot dot backslash *OR* dot dot (trailing backslash is optional).
REM ----- | | set _MYPROGRAMDIR_=%dp0%\..                         <<<<<<<program is back one directory from batch
REM ----- | |                                                                  same as location as previous but using environment variable.
REM ----- | | set _MYPROGRAMDIR_=%SYSTEMROOT%\..\My Utilities     <<<<<<<program is back one directory from the Windows folder
REM ----- | |                                                                  and then forwards into the folder 'My Utilities'
REM ----- | | set _MYPROGRAMDIR_=C:\My Utilities\                 <<<<<<<enclosing quotes are optional; trailing backslash is optional
REM ----- | |                                                                  same location as previous

    set _MYPROGRAMDIR_=

REM ----- ----------------------------------------
REM ----- |SET THE WANTED DIMENSIONS OF THIS CONSOLE WINDOW

    set /a _WINW_=(%_SCREENW_% / 2) + 250
    set /a _WINH_=(%_SCREENH_% / 2) + 150
    set /a _WINX_=(%_SCREENW_% - %_WINW_%) / 2
    set /a _WINY_=(%_SCREENH_% - %_WINH_%) / 2

REM ----- ----------------------------------------
REM ----- |STYLE THIS CONSOLE WINDOW   !!!IMPORTANT!!!
REM ----- |
REM ----- | |IF WE DO NOT USE THE 'MODE' COMMAND HERE ALONG WITH ITS 'COLS/LINES' VALUES THEN
REM ----- | |THE POSITIONING/SIZING OF THIS WINDOW BY 'NIRCMD.EXE' FURTHER DOWN WILL NOT WORK !!!
REM ----- | |
REM ----- | | |SOME COMMANDS WILL OUTPUT A LOT OF LINES AND AND THE CONSOLE DISPLAY WILL BE TRUNCATED
REM ----- | | |RUN THIS FOR AN EXAMPLE=====>   cmd.exe dir "%systemroot%\system32" /a/o/s/4   <=====
REM ----- | | |TO SOLVE THIS PROBLEM, SET THE 'LINES' VALUE OF 'MODE' TO A VERY HIGH NUMBER
REM ----- | | |THE MAXIMUM NUMBER IS 32000 (ON MY SYSTEM); 'MODE' WILL BE IGNORED IF THE NUMBER IS HIGHER !!!  

    color 0A
    mode.com con:cols=%_SCREENW_% lines=10000

REM ----- ----------------------------------------
REM ----- |DELETE THE TEMP TEXT FILE MADE BY 'MonitorInfoView.exe'
REM ----- |COMMENT OUT THE LINE IF YOU DON'T CARE ABOUT DELETING IT

    del /f /q ~TMP.TXT 2>nul >nul

REM >>>>>>>>>> USER INPUT/PREFERENCES ARE ALL SET HERE [END] <<<<<<<<<<<<<<
REM >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


REM ----- RUN THE TASK . . .
nircmd.exe win setsize foreground %_WINX_% %_WINY_% %_WINW_% %_WINH_%
popd

if not defined _MYPROGRAMDIR_ set _MYPROGRAMDIR_=%~dp0
if "!_MYPROGRAMDIR_!" == "." set _MYPROGRAMDIR_=%~dp0
if "!_MYPROGRAMDIR_!" == ".\" set _MYPROGRAMDIR_=%~dp0
pushd %_MYPROGRAMDIR_%
if not exist %_MYPROGRAMDIR_% goto _SKIP_
set _CONVERT_PATH_="%CD%"
set _CONVERT_PATH_=%_CONVERT_PATH_:"=%
set _MYPROGRAMDIR_=%_CONVERT_PATH_%
:_SKIP_
popd

echo ===============================================================================
echo PROGRAM ..............: !_MYPROGRAM_!
if "!_MYPROGRAM_!"=="cmd.exe" (echo PROGRAM DIR ..........: %SYSTEMROOT%\system32) else (echo PROGRAM DIR ..........: !_MYPROGRAMDIR_!)
echo PROGRAM SWITCHES .....: !_MYPROGRAMSWITCHES_!
echo ===============================================================================

if "!_MYPROGRAM_!"=="cmd.exe" (goto _PROGRAM_IS_CMD_) else (goto _PROGRAM_IS_OTHER_)

:_PROGRAM_IS_CMD_
cd /d "%SYSTEMROOT%\system32"
!_MYPROGRAMSWITCHES_!
echo. & echo. & echo.
goto _END_

:_PROGRAM_IS_OTHER_ 
cd /d "!_MYPROGRAMDIR_!"
if "%CD%\!_MYPROGRAM_!" == "%CD%\" goto _ERRORMESSAGE_
if not exist "%CD%\!_MYPROGRAM_!" goto _ERRORMESSAGE_
"!_MYPROGRAMDIR_!\!_MYPROGRAM_!" !_MYPROGRAMSWITCHES_!
echo. & echo. & echo.
goto _END_

:_ERRORMESSAGE_
cls
color 4F
echo ===============================================================================
echo PROGRAM ..............: !_MYPROGRAM_!
echo PROGRAM DIR ..........: !_MYPROGRAMDIR_!
echo PROGRAM SWITCHES .....: !_MYPROGRAMSWITCHES_!
echo ===============================================================================
echo                        ^^!^^!^^!  E R R O R  ^^!^^!^^!
echo.
echo The program has failed to run; the path set by the above values does not exist.
echo Please exit this window and check the values you have set in this batch file.
echo.
echo This batch file is located here:
echo %0
echo. & echo. & echo. & echo. & echo.

:_END_

REM ----- CLEAR VARIABLE VALUES FROM MEMORY . . .
set _PROCESS_ID_=
set _SCREENW_=
set _SCREENH_=
set _MYPROGRAM_=
set _MYPROGRAMSWITCHES_=
set _MYPROGRAMDIR_=
set _WINW_=
set _WINH_=
set _WINX_=
set _WINY_=
set _CONVERT_PATH_=

REM ----- STOP THIS CONSOLE WINDOW FROM CLOSING   !!!IMPORTANT!!! . . .
REM ----- SEE <http://superuser.com/questions/306167/how-to-prevent-the-command-prompt-from-closing-after-execution>
cmd.exe
Error: User Rate Limit Exceeded

Похожие вопросы