Page 1 of 5

Cmdwiz - 54 operation cmd helper tool (now with Unicode)

Posted: 10 Sep 2016 19:46
by misol101
This program has been wedged in between my other two programs cmdgfx.exe and gotoxy.exe for some time. This thread is mostly to get some documentation up.

Now supports Unicode!

What is it?
Cmdwiz is a helper tool to do all sorts of useful things in batch scripts (and outside).

Where is it?
I don't want to maintain yet another archive so I'll point to gotoxy.zip, where cmdwiz.exe is included: http://www.mediafire.com/download/8xywd ... gotoxy.zip
(open link in new tab if it doesn't load)

What operations does cmdwiz support?
As of CmdWiz v1.8, there are currently 54 of them, and they can be divided as follows:
  • 1. Set/get windows/cmd buffer size, position and look
    2. Reading input from keyboard and/or mouse
    3. Setting and saving the current console font
    4. Get character and colors in the buffer/system
    5. Setting the cursor position/look and writing text
    6. Working with strings
    7. Working with timing/delay
    8. Moving and clicking with the mouse cursor and sending key events
    9. Moving, saving or examining blocks of characters
    10. Miscellaneous operations
All operations support "cmdwiz operation /?" to get info on arguments and return values.

There are no operations to write colored text or special characters, which might be expected in a tool such as this.

This is because all that is done by my other tool "gotoxy.exe" (see http://www.dostips.com/forum/viewtopic.php?f=3&t=7129), which has many ways to accomplish that task and much more (note: gotoxy.exe is also included in the above archive).

Also, for more heavy graphics and games, there is "cmdgfx.exe", see http://www.dostips.com/forum/viewtopic.php?f=3&t=7153.


Note on arguments:
I don't follow the normal convention where arguments surrounded by [] are strictly optional.

For cmdwiz (and my other tools), arguments surrounded by [] ARE optional, *but* if you want to specify the following argument(s) (in order from Left to Right), then they are NOT optional.

Example: cmdwiz operation [op1] [op2] [op3 op4]

Here, op1 is optional, as is op2, but to specify op2 you must specify op1. Next comes op3 and op4, for which op1 and op2 must both be given first. Op3/op4 must be specified together, since they are within the same block.

To write the above strictly correct, it would look like: cmdwiz operation [op1 [op2 [op3 op4]]], which I personally find confusing, so I just don't.

Think of it as default arguments in a C++ function. Hopefully the operation is constructed so that you should not want to specify op2 without specifying op1 (though not always true)

Re: Cmdwiz - cmd helper tools

Posted: 10 Sep 2016 20:22
by misol101
1. Set/get the cmd/windows buffer size, position and look

Operations: getconsoledim, setbuffersize, getdisplaydim, getwindowbounds, setwindowpos, setwindowtransparency, setwindowstyle, getwindowstyle, setpalette, getpalette, fullscreen, showwindow, setwindowsize, windowlist, getfullscreen, getdisplayscale

Note that since CmdWiz v1.6, all window/screen coordinates use unscaled display values.

1.0 Using other windows than the console window

Since CmdWiz 1.2, a number of operations can be used for other windows than the console window. These operations are: setwindowpos, setwindowsize, getwindowbounds, setwindowtransparency, showwindow, getwindowstyle, setwindowstyle, insertbmp (setmousecursorpos, getmousecursorpos, and sendkey might also be helpful but no specific window is set)

In order to specify which window to be affected, the last argument of the operation must follow this form:

[/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle[:F]"]

This data can (but does not have to) be obtained by using the cmdwiz windowlist operation.

Note that only one of the options may be used. No spaces are allowed between the switch and the data

/h: must specify the window handle. This handle is guaranteed to be unique per window.
/p: must specify the process id. This id is not necessarily unique. The Cmdwiz operation will stop once it finds the first window with this processId (but since version 1.7 then try to find a main window, see below).
/t: must specify the thread id. This does not appear to work in all cases. Another approach is recommended if possible.
"/n:" must specify the process name. The whole parameter must be within quotes if the name contains spaces. The process name is not necessarily unique per window. Since version 1.7, the search must match only the beginning of the process name (which may or may not be the full name), and it is not case sensitive.
"/w:" must specify the window title. The whole parameter must be within quotes if the title contains spaces. The title is not necessarily unique per window. Since version 1.7, the search must match only the beginning of the title, and it is not case sensitive. To force a FULL title match, it is possible to add :F to the end of the search string.

Since version 1.7, using any other switch than /h and /w will automatically try to find the "main window" of the program, i.e. the visible one. Some programs may have several main windows open, in which case the user will still have to use /h or /w to point to the exact right window.

1.1 getconsoledim

Prints column/row dimensions of current console, OR returns one of these dimensions in ERRORLEVEL.

Usage: cmdwiz getconsoledim [w|h|sw|sh|cx|cy]

Without parameters, getconsoledim will print a line of the form:

WIDTH 80 HEIGHT 50 SCREEN_WIDTH 80 SCREEN_HEIGHT 50 SCROLL_X 0 SCROLL_Y 0

WIDTH and HEIGHT are the actual number of columns and rows of the console buffer, SCREEN_WIDTH/SCREEN_HEIGHT is the amount of visible columns/rows on the screen, and SCROLL_X/SCROLL_Y is the "position" in the buffer, i.e how far we have scrolled into the buffer from the top left position.

If supplying a parameter, nothing is printed, but the requested dimension is returned in ERRRORLEVEL. Use w/h for WIDTH/HEIGHT, sw/sh for SCREEN_WIDTH/SCREEN_HEIGHT, cx/cy for SCROLL_X/SCROLL_Y values.


1.2 setbuffersize

Set the scroll buffer column/row size. It is not a replacement for "mode", since it does not change the number of visible columns/rows, only the size of the scroll buffer.

Usage: cmdwiz setbuffersize [width|keep|- height|keep|-]

The value(s) given can not be smaller than the currently visible number of columns/rows.

For both width and height, you can specify "keep" (or short "k") to mean "keep current value".

To remove a scrollbar (if present), use - for width and/or height.


1.3 getdisplaydim

Get the width or height of the Windows desktop. This may be useful to e.g position the console window with setwindowpos.

Usage: cmdwiz getdisplaydim [w|h] [scaled]

Since version 1.5, the requested result is unscaled by default (i.e. not affected by Windows display scale settings). Supply the "scaled" argument to get the scaled result.

The requested dimension is returned in ERRORLEVEL.


1.4 getwindowbounds

Get the position of the console window (or other window) in screen coordinates or its width/height in pixels.

Usage: cmdwiz getwindowbounds [x|y|w|h] [includeBorders|excludeBorders|alwaysExcludeBorders] [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

By default, returned bounds include the title and borders of the window (including invisible borders in Windows 10). Use excludeBorders (or e for short) as third parameter to disable this. Use alwaysExcludeBorders/a to ignore window settings indicating that the window does not have a border and/or title.

The requested value is returned in ERRORLEVEL.

See 1.0 for information on how to use the last parameter to affect another window than the console window.


1.5 setwindowpos

Set the position of the console window (or other window) in screen coordinates.

Usage: cmdwiz setwindowpos [x|keep y|keep] [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

For both x and y, you can specify "keep" (or short "k") to mean "keep current coordinate".

See 1.0 for information on how to use the last parameter to affect another window than the console window.


1.6 setwindowtransparency

Sets the transparency level of the console window (or other window). The whole window is affected.

Usage: cmdwiz setwindowtransparency [0-100] [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

Note that a value of 100 will make the console window completely invisible!

See 1.0 for information on how to use the last parameter to affect another window than the console window.


1.7 setwindowstyle

Sets or clears a flag in the console window (or other window) properties, affecting its look or behaviour.

Usage: cmdwiz setwindowstyle set|clear standard|extended value1 [value2] ... [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

This operation is rather tricky to use. Please have a look at these two pages: https://msdn.microsoft.com/en-us/librar ... 32600.aspx (for 'standard' style values) and https://msdn.microsoft.com/en-us/librar ... 00543.aspx (extended style values).

To set or clear a flag, first determine if it is a standard or extended flag you want to affect, then copy the corresponding value.

See 1.0 for information on how to use the last parameter to affect another window than the console window.

Examples:

Disable mouse resizing of window: cmdwiz setwindowstyle clear standard 0x00040000L

Disable maximizing window: cmdwiz setwindowstyle clear standard 0x00010000L

Disable all input to window (not recommended...) : cmdwiz setwindowstyle set standard 0x08000000L


1.8 getwindowstyle

Checks if a flag of the console window (or other window) properties is set or not.

Usage: cmdwiz getwindowstyle standard|extended value [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

Returns ERRORLEVEL 1 if style flag set, otherwise 0.

See 1.7 for useful links.

See 1.0 for information on how to use the last parameter to affect another window than the console window.

Example to check if title bar is enabled: cmdwiz getwindowstyle standard 0x00C00000L, followed by echo %ERRORLEVEL%


1.9 setpalette

Sets one or more colors in the cmd window palette (starting from index 0, max 16 colors)

Usage: cmdwiz setpalette [RRGGBB[,RRGGBB...]]

Example (set color 0-2 to pink,white,yellow ): cmdwiz setpalette ff0088,ffffff,ffff00

To restore cmd's default palette, you can use: cmdwiz setpalette 000000,000080,008000,008080,800000,800080,808000,c0c0c0,808080,0000ff,00ff00,00ffff,ff0000,ff00ff,ffff00,ffffff


1.10 getpalette

Prints the RGB values of the current 16 colors of the cmd window. The string can be used as input for setpalette.

Usage: cmdwiz getpalette


1.11 fullscreen

Turns fullscreen use on or off for the console window.

Usage: cmdwiz fullscreen [0|1] [legacy]

Note: The fullscreen operation now uses the official Windows API SetConsoleDisplayMode, whereas previously it used code from carlos fscreen program. However, SetConsoleDisplayMode is not available on older Windows versions such as Windows 7. Therefore, if the initial API call fails, the operation will use the legacy fullscreen mode instead, as well as RETURN ERRORLEVEL -1 to indicate this.

It is also possible to force legacy mode on all machines using the legacy argument.

Note that the API and the legacy fullscreen modes look different: in the legacy mode, there are borders around the screen, and also, the bottom task bar is visible.


1.12 showwindow

Maximize, minimize, or restore the console window (or other window), or set its position in the window hierarchy, or close the window.

Usage: cmdwiz showwindow [minimize|maximize|restore|topmost|top|bottom|close|value:n] [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

If you specify the topmost argument, the window will hereafter become a topmost window, i.e. always be on top of other windows. To disable this, set it to top or bottom.

It is also possible to affect the window in some other ways, using the values at https://msdn.microsoft.com/en-us/librar ... s.85).aspx

See 1.0 for information on how to use the last parameter to affect another window than the console window.

Example: cmdwiz showwindow value:0

will hide the console window completely. Not recommended, because as far as I know you cannot get it back (but the process is still running, as Task Manager will show)


1.13 setwindowsize

Set the size of the console window (or other window) in pixels.

Usage: cmdwiz setwindowsize [w|keep h|keep] [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle"]

For both w and h, you can specify "keep" (or short "k") to mean "keep current size".

See 1.0 for information on how to use the last parameter to affect another window than the console window.


1.14 windowlist

Print a list of all (titled) main windows to stdout.

Usage: cmdwiz windowlist [all]

The output format is the following: window handle|process ID|thread ID|process name|window title

Use the 'all' argument to include untitled windows in the list as well.


1.15 getfullscreen

Return information about the fullscreen status of the cmd window.

Usage: cmdwiz getfullscreen

Returns -1 if failed to get info, 0 if console is windowed, 1 if fullscreen, 2 if 'fake' (legacy) fullscreen


1.16 getdisplayscale

Return the display scale (set in Windows Display settings).

Usage: cmdwiz getdisplayscale

Returns 100 if standard scaling is applied, otherwise the set scaling value

If scaled coordinates from a window operation (e.g. getwindowbounds) is needed, this formula can be used: scaled=unscaled*100/displayscale

Re: Cmdwiz - cmd helper tools

Posted: 10 Sep 2016 20:27
by misol101
2. Reading input from keyboard and/or mouse

Operations: getch, getkeystate, getch_and_mouse, getch_or_mouse, getmouse, flushkeys, getquickedit, setquickedit


2.1 getch

Return scan code of first key in queue, if any.

Usage: cmdwiz getch [noWait]

The key Scan Code is returned in ERRORLEVEL, or 0 if no key was pressed.

If "noWait" is specified, the operation does not block waiting for a key press.

If you want to know the scan codes of some keys for a script, you can either:

1. Find it here: https://msdn.microsoft.com/en-us/librar ... s.60).aspx . For special keys, such as F1, Home, Cursor keys etc, add 256 to the value. So e.g. Shift-F1 would be 256+84 = 340.
2. Use a little loop to print out the scan codes you are interested in, e.g (use Ctrl-Break to end): for /L %a in (1,1,1000) do @cmdwiz getch&echo !errorlevel!

For non-special keys, you could use this in a script to re-map scancodes back into letters/numbers etc:

Code: Select all

set SCHR="()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\] _ abcdefghijklmnopqrstuvwxyz{|}~"
cmdwiz getch&set KEY=!errorlevel!
set LKEY=""
set /A INDEX=%KEY%-40+1
if %KEY% leq 126 if %KEY% geq 40 set LKEY="!SCHR:~%INDEX%,1!"
echo %LKEY%

2.2 getkeystate

Get the state (pressed or not) of specified keys (including mouse keys). This is useful for example if you do not want to wait for key repeat, or if you want to check keys such as Shift/Ctrl/Alt etc.

Usage: cmdwiz getkeystate [any|all|[l|r]ctrl|[l|r]alt|[l|r]shift|[0x]VKEY[h]] [VK2] ...

This command has double output. It will return a bit pattern in ERRORLEVEL representing the pressed state of the given keys, as well as print the states to stdout. If you do not want the printed output, redirect it to nul.

The virtual-key codes needed to check a specific key unfortunately do NOT correspond to the scan codes of the "getch" operation. See this link for codes: https://msdn.microsoft.com/en-us/librar ... 85%29.aspx . In order to check for e.g. "A", you would need to check the pressed state of both VK_SHIFT and 41h ("a").

The virtual-key code input to getkeystate is either decimal or hexadecimal(followed by 'h'). Hexadecimal is recommended, since it can be taken straight from the above link. There are also shorthands for ctrl, alt and shift (and their left/right versions). The keyword "all" is short for: [shift lshift rshift ctrl lctrl rctrl alt lalt ralt]. The keyword "any" means any key (including other keys specified in the same call).

For the output, bit 1 is set if the first given key is pressed, bit 2 is set if the second given key is pressed, etc. The same pattern is true for the written output.

If you are not familiar with bitwise operations then it will probably be easier to redirect the written output to a file and parse that than to use ERRORLEVEL. However, using ERRORLEVEL is likely to be slightly faster and leaves no file traces if you redirect to nul.

To see this operation in action, try: for /L %a in (1,1,5000) do @cmdwiz getkeystate lalt 20h 70h 27

We are checking four keys here: Left-Alt, 20h=Space, 70h=F1, 27=Escape
Pressing and holding one or more of these keys will change 0 to 1 for that key.

To check these keys in a script, here is an example batch file that will hopefully make things a bit more clear:

Code: Select all

@echo off
setlocal
:REPEAT
cmdwiz getkeystate lalt 20h 70h 27 > ks.dat

:: Use errorlevel to get results
set /a "leftAlt=%errorlevel% & 1, space=(%errorlevel% >> 1) & 1, f1=(%errorlevel% >> 2) & 1, escape=(%errorlevel% >> 3) & 1"
if %leftAlt% == 1 echo Bitpattern says: Left-Alt pressed
if %space% == 1 echo Bitpattern says: Space pressed
if %f1% == 1 echo Bitpattern says: F1 pressed

:: OR, use redirected output to get results
for /F "tokens=1,2,3,4 delims= " %%a in (ks.dat) do set /a "leftAlt=%%a, space=%%b, f1=%%c, escape=%%d"
if %leftAlt% == 1 echo Output says: Left-Alt pressed
if %space% == 1 echo Output says: Space pressed
if %f1% == 1 echo Output says: F1 pressed

if %escape% == 0 goto REPEAT

del /q ks.dat>nul
endlocal
In order to check the state of mouse buttons, use this:

Code: Select all

cmdwiz getkeystate 1 2 4 >nul
set /a "left=%errorlevel% & 1, right=(%errorlevel% >> 1) & 1, middle=(%errorlevel% >> 2) & 1"


2.3 getch_and_mouse

There are three operations to get mouse input: getch_and_mouse, getch_or_mouse, and getmouse. The written output from all three follows the exact same pattern, while the ERRORLEVEL output differs slightly.

This operation reports both mouse events and key events that occured since the last run.

Usage: cmdwiz getch_and_mouse [maxWait_ms]

The operation will wait forever for an event unless maxWait_ms (time in milliseconds) is set.

The output from the program comes in two forms. The first is written output. In case there is no event (that is, if the timer timed out), the output will be:

NO_EVENT

Otherwise, it will have the following form:

EVENT KEY_EVENT 0 MOUSE_EVENT 1 MOUSE_X 22 MOUSE_Y 36 LEFT_BUTTON 0 RIGHT_BUTTON 0 LEFT_DOUBLE_CLICK 0 RIGHT_DOUBLE_CLICK 0 MOUSE_WHEEL 0

If MOUSE_EVENT is 0, then there was no mouse event and the rest of the mouse values can be ignored. If KEY_EVENT is 0, then no key was pressed.

Any reported key code has the same scan-code values as used by the operation "getch".

Alternatively, you can read the ERRORLEVEL to get the event information. If there were no events (time-out) the result is -1. Otherwise, the bit pattern follows the form:

kkkkkkkkkyyyyyyyxxxxxxxxWwRLrlM

where M is set if there was a Mouse event, l/L is single/double left click, r/R is single/double right click, w/W is mouse wheel up/down, x/y are mouse coordinates, and k is the KEY (0 means no key pressed)


If you are not familiar with bitwise operations then it will probably be easier to redirect the written output to a file and parse that than to use ERRORLEVEL. However, using ERRORLEVEL is likely to be slightly faster and leaves no file traces if you redirect to nul.

BUT it is also important to note that because of the limited space of the 32 bit value of ERRORLEVEL, there is a max x value of 255 (8 bits) and a max y value of 127 (7 bits) for the column/row. Using the written output there is no such limitation.

To see getch_and_mouse in action, try: for /L %a in (1,1,5000) do @cmdwiz getch_and_mouse

Try pressing the keys or moving the mouse around, clicking etc. Note that you might get mouse events even though x/y coordinates don't seem to change. This is because even the tiniest pixel movement by the mouse will create an event, but it might not change the column and/or row, which are typically several pixels wide/high.

To parse the output in a script, here is an example batch file that will hopefully make things a bit more clear:

Code: Select all

@echo off
setlocal
:REPEAT
cmdwiz getch_and_mouse>mo.dat

:: Use errorlevel to get results
set MR=%errorlevel%
if %MR%==-1 set KEY=0&goto SKIP
set /a "KEY=(%MR%>>22), MOUSE_EVENT=%MR% & 1, LMB=(%MR% & 2)>>1, RMB=(%MR% & 4)>>2, LDBL=(%MR% & 8)>>3, RDBL=(%MR% & 16)>>4, MWD=(%MR% & 32)>>5, MWU=(%MR% & 64)>>6, MX=(%MR%>>7) & 255, MY=(%MR%>>15) & 127"
if "%MOUSE_EVENT%"=="0" echo Errorlevel says: Key value: %KEY% & goto SKIP
echo Errorlevel says: Mouse x,y: %MX%,%MY% LMB=%LMB% RMB=%RMB% LDBL=%LDBL% RDBL=%RDBL% UP=%MWU% DOWN=%MWD%
:SKIP

:: Use written output to get results
for /F "tokens=1,3,5,7,9,11,13,15,17,19,21 delims= " %%a in (mo.dat) do set EVENT=%%a&set KEY=%%b&set MOUSE_EVENT=%%c&set MX=%%d&set MY=%%e&set LMB=%%f&set RMB=%%g&set LDBL=%%h&set RDBL=%%i&set MWHEEL=%%j
if "%EVENT%"=="NO_EVENT" set KEY=0&goto SKIP2
if "%MOUSE_EVENT%"=="0" echo Written output says: Key value: %KEY% & goto SKIP2
echo Written output says: Mouse x,y: %MX%,%MY% LMB=%LMB% RMB=%RMB% LDBL=%LDBL% RDBL=%RDBL% WHEEL=%MWHEEL%
:SKIP2
echo.

if not %KEY% == 27 goto REPEAT

del /q mo.dat>nul
endlocal

2.4 getch_or_mouse

Get key or mouse events. Very similar to "getch_and_mouse" but does not report both mouse and key events at the same time.

Usage: cmdwiz getch_or_mouse [maxWait_ms]

The printed output looks exactly the same as for getch_and_mouse (see above).

For ERRORLEVEL, the value is -1 if there was no event (time-out). If there was a mouse event, the pattern is:

yyyyyyyyyyxxxxxxxxxxx---WwRLrl0

and if there was a key event, the pattern is:

kkkkkkkkkk1

This means that the first bit determines if it is a key or mouse event.

Parsing the mouse event from ERRORLEVEL is the same as for getch_and_mouse, except for the x and y coordinates. Use "(!errorlevel!>>10) & 2047" and "(!errorlevel!>>21 & 1023" to get them.

Note that you can get larger x/y values than for "getch_and_mouse", max x is 2047 instead of 511 and max y is 1023 instead of 127.


2.5 getmouse

Get mouse events.

Usage: cmdwiz getmouse [maxWait_ms]

getmouse is very similar to "getch_or_mouse", except it does not report key events.

The ERRORLEVEL pattern is the same, except the first bit can be ignored

yyyyyyyyyyxxxxxxxxxxx---WwRLrl-

NOTE: Even though getmouse does not report key events, it will still unfortunately consume the key events it gets. Therefore, calling "cmdwiz getch" after getmouse will not produce the desired result. If you need to get both mouse and key events, use "getch_or_mouse" or "getch_and_mouse" operations. That said, the "getkeystate" operation does work together with "getmouse".


2.6 flushkeys

Flush all remaining keys in the pressed key buffer

Usage: cmdwiz flushkeys

If a program lags behind in its processing of keys (by e.g. doing a heavy task while not checking for key presses), there might be any number of queued up key presses to process once that task ends. If you want to discard any remaining unprocessed key presses up until the current point, use the flushkeys operation.


2.7 getquickedit

Determines whether the console is in quickedit mode. In quick-edit mode, the mouse can be rapidly used to select/copy/paste text with left/right mouse buttons. In case you want to use mouse input in a script it is generally advisable to turn off quickedit.

Usage: cmdwiz getquickedit

Returns an ERRORLEVEL of 1 if quickedit is enabled, otherwise 0.


2.8 setquickedit

Enables or diables quickedit mode. See getquickedit for more info.

Usage: cmdwiz setquickedit [0|1]

Re: Cmdwiz - cmd helper tools

Posted: 11 Sep 2016 14:41
by misol101
3. Setting and saving the current console font

Operations: setfont, savefont


3.1 setfont

Sets the current console font based on either a bitmap font index, or a saved font specification file.

Usage: cmdwiz setfont [0-9|filename]

Font index 0 to 9 will set the corresponding bitmap font.

If you specify a filename, the file given must have been saved with the "savefont" operation


3.2 savefont

Writes specifications of the current font to a file

Usage: cmdwiz savefont [filename]

Note that no font image data is saved, only the specifications of the fonts (i.e. its name, size, etc)

This means two things:
1. These files are rather small
2. If you use the file on a different computer, "setfont" will only work if the same font is available on that computer too. I guess "Consolas" and "Lucida Console" are pretty much standard these days at least.

Also note that for non-bitmap fonts, you will need to set the font/size manually in "Properties" before you use "savefont", but once it is saved, it can be restored from the file at any time using "setfont".

Savefont/setfont can also be used to restore the initially used font even when it's not known which one that was:

Code: Select all

cmdwiz savefont tmpfont.fnt
cmdwiz setfont 5
echo Doing some stuff...
cmdwiz setfont tmpfont.fnt
del /Q tmpfont.fnt>nul

Re: Cmdwiz - cmd helper tools

Posted: 16 Sep 2016 17:23
by misol101
4. Get character and colors in the buffer/system

Operations: getconsolecolor, getcharat, getcolorat


4.1 getconsolecolor

Returns either the foreground or background color index currently used by the console.

Usage: cmdwiz getconsolecolor [fg|bg]

The color index is returned in ERRORLEVEL.

The console colors can be set with cmd's standard "color" command.


4.2 getcharat

Returns the character (extended ASCII value) at the given buffer position.

Usage: cmdwiz getcharat [x|k y|k]

Specify k(for "keep") for x and/or y to use the current cursor position in x and/or y

The result is returned in ERRORLEVEL.


4.3 getcolorat

Returns either the foreground or background color index at the given buffer position.

Usage: cmdwiz getcolorat [fg|bg x|k y|k]

Specify k(for "keep") for x and/or y to use the current cursor position in x and/or y

The result is returned in ERRORLEVEL.

Re: Cmdwiz - cmd helper tools

Posted: 16 Sep 2016 18:10
by misol101
5. Setting the cursor position/look and writing text

Operations: getcursorpos, setcursorpos, showcursor, print


5.1 getcursorpos

Returns either the x(column) or y(row) position of the cursor

Usage: cmdwiz getcursorpos [x|y]

The value is returned in ERRORLEVEL.


5.2 setcursorpos

Sets the cursor position in the buffer.

Usage: cmdwiz setcursorpos [x|keep y|keep]

Specify k or keep to use the current cursor position for x and/or y.

Note that setting the cursor position also automatically scrolls the buffer (if needed) to make the cursor visible. This can be used to continously scroll step by step in the buffer.


5.3 showcursor

Show or hide the cursor, optionally changing its appearance.

Usage: cmdwiz showcursor [0|1] [show percentage 1-100 (default 25)]

A value of 0 hides the cursor, 1 shows it. The second, optional parameter sets the size of the cursor.

The return value in ERRORLEVEL is -1 on error, otherwise it indicates whether or not the cursor was previously showing. A value of 0 means the cursor was not visible, a value of 1-100 means the cursor was on with that show percentage.


5.4 print

Print the given string to stdout.

Usage: cmdwiz print ["string"]

The surrounding string quotes are not printed.

The string can use the following escape sequences:
\a plays a beep sound (prints ^G)
\b prints a backspace
\e prints an escape character
\n prints a newline
\r prints a carriage return
\t prints a tab
\' prints a '
\" prints a "
\\ prints a \
\xhh prints hexadecimal ascii character hh (e.g. \x21=! \x25=%)
\uhhhh prints hexadecimal Unicode point hhhh (e.g. \u03cf for a greek glyph (if supported by font))

NOTE: for advanced text output using colors, moving the cursor around, wrapping, special characters etc, use my other tool "gotoxy.exe" (http://www.dostips.com/forum/viewtopic.php?f=3&t=7129), or possibly "cmdgfx.exe" (http://www.dostips.com/forum/viewtopic.php?f=3&t=7153)

Re: Cmdwiz - cmd helper tools

Posted: 16 Sep 2016 18:13
by misol101
6. Working with strings

Operations: stringfind, stringlen


6.1 stringfind

Searches for a string inside another string

Usage: cmdwiz stringfind [orgstring findstring] [startindex] [noCase]

This operation attempts to find findstring inside orgstring.
If the search was successful, ERRORLEVEL is set to the 0-based index position in orgstring where findstring was found. If the string was not found, the return value is -1.

If startindex is set, the search in orgstring starts from the given index position.

If the noCase argument is given, the string search is not case sensitive.

It is a good idea to surround both strings with quotes (quotes are not included in the search).


6.2 stringlen

Returns the length of a given string

Usage: cmdwiz stringlen [string]

The length of the string (number of characters) is returned in ERRORLEVEL.

It is a good idea to surround the string with quotes (quotes are not included in the string length).

Re: Cmdwiz - cmd helper tools

Posted: 22 Sep 2016 17:40
by misol101
7. Working with timing/delays

Operations: delay, gettime, await


7.1 delay

Pauses for the specified amount of time

Usage: cmdwiz delay [ms]

The execution halts for the amount of milliseconds given. No message is printed.


7.2 gettime

Retrieves the number of milliseconds that have elapsed since the system was started

Usage: cmdwiz gettime

The result is returned in ERRORLEVEL.

This operation is useful for measuring time (divide by 1000 to get seconds), or in conjunction with await (below).


7.3 await

Waits up to the given amount of milliseconds

Usage: cmdwiz await [oldtime] [waittime]

This operation wait for up to waittime ms, depending on how much time passed since oldtime.

A typical use case would be something like:

Code: Select all

cmdwiz gettime
set STARTTIME=%errorlevel%
...do some stuff
cmdwiz await %STARTTIME% 5000

If "some stuff" took 3.5s to complete then await will wait the remaining 1.5 s. If it took longer than 5s then it will not wait at all.

Re: Cmdwiz - cmd helper tools

Posted: 22 Sep 2016 17:41
by misol101
8. Moving and clicking with the mouse pointer and sending key events

Operations: getmousecursorpos setmousecursorpos showmousecursor sendkey


8.1 getmousecursorpos

Get the x or y position of the mouse cursor in pixels from the top left of the screen

Usage: cmdwiz getmousecursorpos [x|y]

Note that this is not the column/row position in the console window, but the actual pixel position of the mouse pointer.

The value is returned in ERRORLEVEL.


8.2 setmousecursorpos

Sets the mouse cursor position, optionally followed by a click

Usage: cmdwiz setmousecursorpos [x|keep y|keep] [l|r|d|u|m|wu|wd|wl|wr] [wheelAmount]]

This operation first moves the mouse pointer to the given position. For both x and y, you can specify "keep" (or short "k") to keep the current position.

If a click argument was given, it follows:

l: simulates a left click with the mouse
r: simulates a right click with the mouse
d: simulates holding the left mouse key down
u: simulates releasing the left mouse key
m: simulates a middle click with the mouse
wu/wd: simulates moving the vertical mouse wheel up or down. Use optional wheelAmount argument if you want a bigger movement than 1 step.
wl/wr: simulates moving the horizontal mouse wheel left or right. Use optional wheelAmount argument if you want a bigger movement than 1 step.

d and u can be used together for dragging.

A left or right or middle double-click can be simulated by running the same setmousecursorposition operation twice.


8.3 showmousecursor

Hide or show the mouse cursor over the cmd window

Usage: cmdwiz showmousecursor [0|1]

Note: Unfortunately this operation does not work on Windows 10, unless using the legacy console.

8.4 sendkey

Simulates keyboard input events

Usage: cmdwiz sendkey [[0x]VKEY[h] p|d|u [repeatCount]] | "string"

Sendkey either emulates a single key press (see below), or it sends a string of key presses (see further down).

The virtual key code (VKEY) values can be found here: https://msdn.microsoft.com/en-us/librar ... 85%29.aspx
The easiest way to use them is to copy/paste them from the web page in the 0x?? format.

'p', 'd' or 'u' specifies what kind of event is sent:

p: simulates that the key was both pressed and released
d: simulates that the key was pressed down but has not been released
u: simulates that a previously pressed key was released

Specify a number 2 or more as [repeatCount] to repeat the key press that many times.

Example (simulates holding down ALT, then pressing/releasing the TAB key, which will bring up the ALT-TAB menu)

Code: Select all

cmdwiz sendkey 0x12 d & cmdwiz sendkey 0x09 p
Other example, save snapshot by pressing PrtScr

Code: Select all

cmdwiz sendkey 0x2c p

For use of "string", only the following keys are directly supported, the rest are keyboard layout specific: space a-z A-Z 0-9 .,+-*/. Use prefix $ for Shift, ^ for Ctrl, @ for Alt, { for Alt-Gr, [ for Win-key, \ for Enter,
} for Tab key.

Note that there is no sure-fire way to send for example a "!" character, since it depends on the keyboard layout. On most keyboards, the string "$1" (shift followed by 1) will do the trick.

Example (writes a string, followed by attempting to write a !, followed by pressing Enter and then a second string):

Code: Select all

cmdwiz sendkey "Hello$1\World..."

Re: Cmdwiz - cmd helper tools

Posted: 22 Sep 2016 17:56
by misol101
9. Moving, saving or examining blocks of characters

Operations: copyblock, moveblock, saveblock, inspectblock


9.1 copyblock

Copy a block of characters in the screen buffer from one place to another

Usage: cmdwiz copyblock [x y width height newX newY]

If the block is wider or higher than the buffer or x/y is outside the buffer, the operation will fail and a negative ERRORLEVEL value is returned.

Overlapping blocks are ok.


9.2 moveblock

Move a block of characters in the screen buffer from one place to another

Usage: cmdwiz moveblock [x y width height newX newY] [char] [fgcol] [bgcol]

If the block is wider or higher than the buffer or x/y is outside the buffer, the operation will fail and an ERRORLEVEL other than 0 is returned.

Unless otherwise specified, the area where the block used to be is filled with blankspace characters.
It is possible to specify exactly which character and in which color will fill the blank space using the last three parameters. Char can be specified either as char or as a hex value, fgcol/bgcol can be hex or decimal.


9.3 saveblock

Saves a block of characters from the screen buffer to file, including color information

Usage: cmdwiz saveblock [filename x y width height] [encode|forcecode|nocode|txt] [transparent char] [transparent bgcolor] [transparent fgcolor]

The filename will automatically have an extension added to it. The default is ".gxy", which is a file format for colorized text used by my tools cmdgfx and gotoxy. However, if the encoding argument (argument 6) is "txt", the file is saved as text and will have the file extension ".txt". For more information on the gxy file format, see the syntax of gotoxy. It is comparable to ANSI escape sequences in order to change colors, print special characters, position the cursor etc.

If the block is wider or higher than the buffer or x/y is outside the buffer or the file cannot be saved, the operation will fail and an ERRORLEVEL lower than 0 is returned.

Argument 6 specifies which characters in the file should be stored as plain text and which should be encoded. A file with no encoding will be smaller and more readable from a human perspective, but could cause issues when printed. The default setting is encode, which will leave A-Z, a-z, blankspace and numbers unchanged, but encode all other characters. Forcecode will encode all characters, nocode encodes no characters, and txt is like nocode but with no colors saved, and with file extension .txt rather than .gxy.

It is possible to make part of the gxy file transparent. This is controlled by the last 3 arguments. If only a transparent char is specified, then all such chars in the input will be transparent in the output. If a bgcolor is given, the previous statement is true, but also the bgcolor needs to match. If an fgcolor is specified, the previous two statements are true, but also the fgcolor needs to match.

It's worth noting that a gxy file with no transparency saved can still be printed as transparent, see the last example below.

To show the saved gxy file, you can use gotoxy.exe in one of two ways (change 0 0 to k k to print at the current cursor position):

Code: Select all

gotoxy 0 0 file.gxy
gotoxy 0 0 "\I:file.gxy;"

The equivalent for cmdgfx is below. With cmdgfx, gxy files can also be used as textures for 3d.

Code: Select all

cmdgfx "image file.gxy 0 0 0 -1 0,0" p

The gotoxy archive also contains a file called editor.bat which can create/edit gxy files. Either specify a file name as first argument to editor.bat, or load a file during runtime by pressing F1 or Shift-F1.

Finally, to print a gxy file as partly transparent even if the gxy file has no transparency (here, all BLANKSPACE characters will be transparent, no matter the color):

Code: Select all

gotoxy 0 0 "\T20kk0\I:file.gxy;"
cmdgfx "image file.gxy 0 0 0 20 0,0" p



9.4 inspectblock

Check for the presence or exclusiveness of one or more characters within a screen buffer block

Usage: cmdwiz inspectblock [x y width height inclusive|exclusive char1] [char2] [char3] ...

This operation can be used e.g. for simple collision detection in games. See the script world.bat in the gotoxy archive for an example.

If the block is wider or higher than the buffer or x/y is outside the buffer, the operation will fail and an ERRORLEVEL of -1 is returned.

Char(s) can be given either as a hexadecimal ASCII value or as a printed character.

If inclusive is specified as argument 5, the output will be set depending on the *presence* of the char(s) in the block, otherwise it's set depending on whether or not ONLY the specified char(s) were present in the block.

For inclusive, the ERRORLEVEL set is a bit pattern representing the presence of the given char(s).
If only one char is given, ERRORLEVEL will be set to 1 if the char was found in the block. If two chars are given, bit 1 in ERRORLEVEL is set if char 1 was found, and bit 2 is set if char2 was found, and so on.

For exclusive, ERRORLEVEL is always 0 or 1. The result is 1 if only the given char(s) were present in the block, otherwise 0.

Example:

Code: Select all

cmdwiz inspectblock 0 0 10 10 inclusive 20 A & set RES=!errorlevel!
set /a "B1=!RES! & 1" & if !B1! gtr 0 echo One or more blankspaces were found in the block
set /a "B2=!RES! & 2" & if !B2! gtr 0 echo One or more A's were found in the block

cmdwiz inspectblock 0 0 10 10 exclusive 20 A & set RES=!errorlevel!
if %RES% == 1 echo Blankspace's and/or A's were the ONLY characters in the block

Re: Cmdwiz - cmd helper tools

Posted: 24 Sep 2016 14:46
by misol101
10. Miscellaneous operations

Operations: insertbmp, playsound, getexetype, cache, gettitle, gxyinfo, gettaskbarinfo, server


10.1 insertbmp

Insert a bitmap image into the console window (or other windows)

Usage: cmdwiz insertbmp [file.bmp x y] [[z]|[w h]] [bitOp] [/h:HWND|/p:pId|/t:tId|"/n:processName"|"/w:windowTitle[:F]"|/D]

Only bmp files are supported. The image is placed at the given x/y position from the top left of the console client area.

Optional size argument(s) can be given in one of two ways:

z: A percentage value. 100 is original size, 200 is double size, etc.

w h: A given width and height in pixels. Aspect ratio is not preserved.

Bitop's are: SRCCOPY (default), SRCPAINT, SRCAND, SRCINVERT, SRCERASE, NOTSRCCOPY, NOTSRCERASE, DSTINVERT, BLACKNESS, WHITENESS

(see https://msdn.microsoft.com/en-us/librar ... s.85).aspx for an explanation of these bitwise operators. )

See section 1.0 for information on how to use the last parameter to insert the bitmap into another window than the console window.

Note that the optional last parameter also contains the switch /D. Using the /D switch, the bitmap will not be placed inside any window, but instead it will be placed directly on the display, on top of all windows. Coordinates 0,0 represesent the top left pixel of the desktop.


RETURN: 0 on success, -1 if failed to load file

Try something like:

Code: Select all

cls
cmdwiz insertbmp 123.bmp 10 10 100 SRCPAINT
cmdwiz insertbmp 123.bmp 120 20 100 SRCPAINT

or perhaps:

mode 80,50
color 0f
set
cmdwiz insertbmp 123.bmp -200 -200 1200 990 SRCAND

10.2 playsound

Plays a sound file

Usage: cmdwiz playsound [filename.wav]

Only .wav files are supported.

The file is played synchronously. For asynchronous playing, use "start /B cmdwiz playsound file.wav", or possibly "start /MIN" instead.


10.3 getexetype

Determine the executable type (if any) of a file

Usage: cmdwiz getexetype [file]

If an error occured, -1 is returned. Otherwise, ERRORLEVEL is set according to the following list:

0 Unable to determine the type
1 Console application or .bat file
2 MS-DOS .exe or .com file
3 Windows application


10.4 cache

Put files in Windows file cache

Usage: cmdwiz cache [filelist] [reportFailedOpen]

In some situations it's advantageous to make sure files are in Windows file cache, since any subsequent operations with those files will be faster. For example, if you show a number of gxy files after each other in an animation, you can ensure a better flow by first putting all the files used into the file cache.

The filelist should be a plain text file (Ansi, Utf-8 or Utf-16 LE) with path/filename to one or more files, each on its own line.

If the second argument is given, the operation will report any files in the file list that could not be opened. The default behavior is to simply ignore this.


10.5 gettitle

Prints the title of the console window to stdout

Usage: cmdwiz gettitle [strip]

The title includes the name of the current script running, or if no script is running, the command itself. To get the base title only, specify the strip option.


10.6 gxyinfo

Print information about dimensions and properties of a gxy (or txt, pcx, bmp, bxy) file

Usage: cmdwiz gxyinfo [filename.gxy|txt|bmp|bxy|pcx] [ignoreCodes]

Returns -1 on error, otherwise 0.

First of all, the operation attempts to print the dimensions (width x height) of the file. Note that gxy files are not necessarily block-shaped, so a dimension of e.g. 10x10 does not necessarily mean that all lines are 10 characters wide, only that the longest line has that many characters.

Furthermore, the operation prints information on things such as transparency, use of color codes, use of special codes only supported by gotoxy (but not cmdgfx) etc.

If the input file is a text file, this analysis might be incorrect, in which case the 'ignoreCodes' argument can be given. In this case, only the dimension is printed.

As cmdwiz is a companion program to cmdgfx, gxyinfo can also return dimension info about bmp(24 bit), bxy, and pcx (256 color) files.

To get dimensions of a file into variables, use something like:

Code: Select all

for /F "tokens=1,2,3,4" %%a in ('cmdwiz gxyinfo "myfile.gxy"') do @if "%%a"=="Dimension:" set /a IMGW=%%b, IMGH=%%d

10.7 gettaskbarinfo

Prints or returns information about Windows taskbar

Usage: cmdwiz gettaskbarinfo [w|h|x|y|a|p]

If no extra argument is given, the operation prints info in the form: X 0 Y 1040 W 1920 H 40 HIDE 0 POS 0

Specify argument x to get x position of taskbar in ERRORLEVEL, y to get y position, w to get width, h to get height, a to get auto-hide setting of the taskbar, p to get taskbar position alignment (see below).

Position alignment: 0=bottom, 1=top, 2=left, 3=right.


10.8 server

Starts Cmdwiz server, and does not stop until Ctrl-C is pressed or "cmdwiz: server quit" is sent to it via stdin.
The server is useful to smoothly animate things like window position, mouse cursor position, window transparency, etc.

Usage: cmdwiz server [quit]

Only these operations can be executed through the server:
setbuffersize setpalette setwindowpos setwindowsize setwindowtransparency print setcursorpos showcursor sendkey setmousecursorpos copyblock moveblock insertbmp server

Once the server is running, execution of the current script stops. Hence, a setup such as the below is recommended (the script calls itself and then sends commands to the server):

Code: Select all

@echo off
if not defined _ (
	set _=.
	call %0 %* | cmdwiz.exe server
	set _=
	goto :eof
)

for /l %%1 in (1,1,1000) do (
	echo "cmdwiz: setwindowpos %%1 300"
)

echo "cmdwiz: server quit"
When running this, there is a big risk that it runs too fast to see much of the animation. In order to control the speed of the animation, use cmdgfx_input.exe, which is also included in the Cmdwiz archive (see the thread on Cmdgfx (viewtopic.php?t=7153, page 6, post #85) for more info on cmdgfx_input.exe).

Using cmdgfx_input.exe, the script may look like this, and animate at around 50 FramesPerSecond:

Code: Select all

@echo off
if not defined _ (
	set _=.
	cmdgfx_input.exe knW10 | call %0 %* | cmdwiz.exe server
	set _=
	goto :eof
)

for /l %%1 in (1,3,1000) do (
	set /p INPUT=
	for /f "tokens=6" %%A in ("!INPUT!") do ( set /a KEY=%%A 2>nul )
	
	echo "cmdwiz: setwindowpos %%1 300"
)

echo "cmdwiz: server quit"
title input:q
See the included example server-cmdwiz-gotoxy-test.bat for a more thorough use of cmdgfx_input and cmdwiz server.


A note on using Cmdwiz server with other windows than the console window:

Finding another window than the console for cmdwiz operations (see section 1.0 for details) is a rather slow task, as it has to search through all open windows. Since the point of Cmdwiz server is to be able to animate smoothly, Cmdwiz will cache the latest window it found, and as long as the argument given to find the window does not change, the window will be re-used without a new search.

Therefore it will also be much faster running several continuous commands on a single window than to use it on many windows after each other.

Re: Cmdwiz - cmd helper tools

Posted: 25 Sep 2016 07:27
by misol101
Alright, all done. A version with a few updates/fixes will appear soon.

If anybody has bug reports, ideas for other operations, or additions to existing ones, do tell.

Re: Cmdwiz - cmd helper tools

Posted: 25 Sep 2016 10:56
by aGerman
Seems you want to compete with NirCmd :lol:

I have a pretty basic suggestion. As you may know Windows works with Unicode (aktually UTF-16 LE) internally. Thus, I strongly advise you to use Unicode in your applications also. In particular if you pass a filename or path with non-ASCII characters (and I know the Swedish alphabet contains some of them too) you will get in trouble.
Unfortunately MinGW/GCC doesn't support wmain/_tmain in order to receive arguments as "wide" strings directly. It's not that easy to work around this limitation, especially if you want to have a cross-compiler code. (MS decided to impede the usage of __wgetmainargs with Visual Studio 2015.)
I'll send you another code of mine (via PM) that you may or may not include in your tool collection. Its purpose is to close a window (which is similar to clicking the red x button). It's not the same as taskkill because you are able to choose what window of the process should be closed and it gives an application the opportunity to cleanup in the window message loop.
Nevermind. It shows how to work around the missing _tmain...

Steffen

Re: Cmdwiz - cmd helper tools

Posted: 26 Sep 2016 02:35
by misol101
aGerman wrote:Seems you want to compete with NirCmd :lol:


Not exactly, it's supposed to be tools for the console only, I just threw in a few things to move mouse cursor pointer etc for fun :) But I am tempted to add an operation like FindWindow and allow the returned handle to be used for various things. But then again, there are already good tools for this kind of stuff like AutoHotkey, so I don't think I should (where will it end? ;) )

aGerman wrote:I strongly advise you to use Unicode in your applications also. In particular if you pass a filename or path with non-ASCII characters (and I know the Swedish alphabet contains some of them too) you will get in trouble.
I'll send you another code of mine (via PM) that you may or may not include in your tool collection.


Thanks Steffen! Yes, Unicode is on the todo-list. I suppose since I mostly made this tool for myself it just wasn't a priority. Swedish chars actually works ok for me, I guess it depends on the codepage used.

I will have a look at your code soon.

Re: Cmdwiz - cmd helper tools

Posted: 26 Sep 2016 14:35
by aGerman
misol101 wrote:But I am tempted to add an operation like FindWindow and allow the returned handle to be used for various things.

FindWindow? Pretty much the same as my tool already does :wink: Seems you could reuse quite a lot of that code if you want.

Steffen