Thursday 26 December 2019

ColourText changes the colour of the text to be printed. This technique is the ONLY one that will work on all Windows version.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.

To use

ColourText <ColourOfText> <ColourOfTextWhenFinished> [Text]

Also the CLS command becomes interesting. Color command without parameters resets all colours to startup colours.

To get the colour code add the following numbers together. Use Calculator in programmers mode. These are hex numbers. They can be added together eg Red + Blue + FG Intensity = 13 = D. As 10+ wasn't used the background will be black. Colour codes MUST be two characters, eg 08 not 8.

FOREGROUND_RED = &H4     '  text color contains red.
FOREGROUND_INTENSITY = &H8     '  text color is intensified.
FOREGROUND_GREEN = &H2     '  text color contains green.
FOREGROUND_BLUE = &H1     '  text color contains blue.
BACKGROUND_BLUE = &H10    '  background color contains blue.
BACKGROUND_GREEN = &H20    '  background color contains green.
BACKGROUND_INTENSITY = &H80    '  background color is intensified.
BACKGROUND_RED = &H40    '  background color contains red.

So black background is 0 while white is F0 (adding 10 + 20 + 40 + 80). Red on white is f4.



REM 2 files follow
REM ColourText.bat
REM Compiles ColourText.vb to ColourText.exe
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\ColourText.exe" "%~dp0\ColourText.vb" /verbose
pause



'ColourText.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication  
Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&

Sub Main()
    Dim hOut as Long
    Dim Ret as Long
    Dim Colour As Long
    Dim Colour1 As Long
    Dim Text As String
    hOut  = GetStdHandle(STD_OUTPUT_HANDLE)
    Colour = CLng("&h" & Split(Command(), " ")(0))
    Colour1 = Clng("&h" & Split(Command(), " ")(1))
    Text = Mid(Command(), 7)
    Ret = SetConsoleTextAttribute(hOut,  Colour)
    Console.Out.WriteLine(text)
    Ret = SetConsoleTextAttribute(hOut, Colour1)
End Sub
End Module

Wednesday 25 December 2019

GetConsoleColour.exe prints the current console colour and returns an errorlevel with the value

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
;Two files follow
REM GetConsoleColour.bat
REM This file compiles GetConsoleColour.vb to GetConsoleColour.exe
REM GetConsoleColour.exe prints the current console colour and returns an errorlevel with the value
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\GetConsoleColour.exe" "%~dp0\GetConsoleColour.vb" 
pause




'GetConsoleColour.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication 
 
Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Declare Function GetConsoleScreenBufferInfo Lib "kernel32" (ByVal hConsoleOutput As Integer, ByRef lpConsoleScreenBufferInfo As CONSOLE_SCREEN_BUFFER_INFO) As Integer
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&

  _
Public Structure COORD
 Public x As Short
 Public y As Short
End Structure

  _
Public Structure SMALL_RECT
 Public Left As Short
 Public Top As Short
 Public Right As Short
 Public Bottom As Short
End Structure

  _
Public Structure CONSOLE_SCREEN_BUFFER_INFO
 Public dwSize As COORD
 Public dwCursorPosition As COORD
 Public wAttributes As Integer
 Public srWindow As SMALL_RECT
 Public dwMaximumWindowSize As COORD
End Structure 


Sub Main()
 Dim hOut as IntPtr
 Dim Ret as Integer
 Dim CSBI as Console_Screen_Buffer_Info
 hOut  = GetStdHandle(STD_OUTPUT_HANDLE)
 Ret = GetConsoleScreenBufferInfo(hOut, CSBI)
 Console.Writeline(Hex(CSBI.wAttributes))
 Environment.ExitCode = CSBI.wAttributes
End Sub
End Module

Wednesday 18 December 2019

Decoding Errors

Informational Posts

Decoding Errors
Decoding Errors
 
-2147220978 style numbers are 32 bit signed integers, convert to hex with calculator.
 
Windows errors (smallish numbers) and  COM HResults (typically, but with exceptions, start with an 8 as in 0x80040154) are defined in WinError.h, except 8007nnnn where you look up the Window error number that it contains.
 
As a general rule Windows errors are less than 65,535 (0xFFFF). Errors starting 0x80000001 are Component Object Model (COM) HResults. Errors starting 0xC0000001 are NTStatus results. Errors starting 0xD0000001 are also NTStatus values returned in a HResult.
 
NTStatus errors (typically but not always start with an C as in 0xC0000022) are defined in NTStatus.h. 
 
.h files are the best source because it includes the symbolic name of the error which can give clues such as the source of the error. FormatMessage doesn't give the symbolic name only the description.
 
You get these files by downloading the Platform SDK (it's gigabytes)

https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/
 
If you just want the two files I have them on my skydrive so I can reference them anywhere I go.

https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 (but they are from 2006)
 
Note internet errors (12,000 - 12,999) are windows errors but are specified in wininet.h also available above. 
 
There are errors defined in other .h files. But 99% are in the three above.
 
Structure of HResults and NTStatus Codes
 
The most significant bit in HResults, and the two most significant bits in NTStatus are set on error. Hence Hresults start 8 on error and NTStatus starts C on Error. The next 14 or 15 bits are reserved and some specify the facility - what area the error is in. This is the third and fourth number when reading hex. EG 0xnn07nnnn - An HResult facility code 7 is a normal Windows' error (returned from a COM program - hence it's returned as a HResult). Facility codes are defined in Winerror.h for HResults and NTStatus.h for NTStatus codes. They are different.
 
 
To Decode 0x8003nnnn Errors
 
HResults with facility code 3 means the HResult contains OLE Structured Storage errors (0x0 to 0xff). These are the same as Dos error codes. These don't seem to be in Windows' header files and the list of codes is at the end of this post.

 
To Decode 0x8004nnnn Errors
 
HResults with facility code 4 means the HResult contains OLE errors (0x0 to 0x1ff) while the rest of the range (0x200 onwards) is component specific errors so 20e from one component will have a different meaning to 20e from another component.

 

This is why the source of the error is extra important for errors above 0x80040200.

 

To Decode 0x8007nnnn Errors
 
HResults with facility code 7 means the HResult contains a Windows' error code. You have to look up the Windows' error code not the HResult.

 
To decode 0x80070002. The 0x means it's a hexadecimal number, the 8 means error, the first 7 means it a windows error, and the rest of the number, 2, is the actual Windows error.
 
To look up the error we need it in decimal format. Start Calculator (Start - All Programs - Accessories - Calculator) and choose View menu - Scientific, then View menu - Hex. Enter 2. Then View menu -  Decimal. It will say 2.
 
Start a Command Prompt (Start - All Programs - Accessories - Command Prompt) and type
 
net helpmsg 2
 
and it will say
 
The system cannot find the file specified.
 
or look it up in winerror.h
 
//
// MessageId: ERROR_FILE_NOT_FOUND
//
// MessageText:
//
// The system cannot find the file specified.
//
#define ERROR_FILE_NOT_FOUND             2L
 
To Decode 0x8019nnnn Errors
 
HResults with facility 0x19 are HTTP errors. Codes under 16,384 (0x4000) are the same as HTTP errors, eg HTTP status 404: The requested URL does not exist on the server is 0x80190194 (0x194 = 404). Codes 16,384 and higher are BITS specific.

To Decode 0xDnnnnnnn Errors
 
HResults starting 0xD are an HResult with a NTStatus value in it. Just cange the lead D to a C and treat as an NTStatus (Hresult = NTStatus OR 10000000).

 

Wednesday 11 December 2019

Brief Introduction to the Windows' Debugger

Informational Posts

Brief Introduction to the Windows' Debugger
Windbg is from Debugging Tools For Windows.

Download and install Debugging Tools for Windows

 http://msdn.microsoft.com/en-us/windows/hardware/hh852363

Install the Windows SDK but just choose the debugging tools.

Create a folder called Symbols in C:\

Start Windbg. File menu - Symbol File Path and enter

 srv*C:\symbols*http://msdl.microsoft.com/download/symbols

then (for example)

 windbg -o -g -G c:\windows\system32\cmd.exe /k batfile.bat

There is an automatic breakpoint set after loading but before any code runs and one at the end after all code has finished but before being terminated. This allows you to examine memory etc before and after the code has run. Press g to continue.

You can press F12 to stop it and kb will show the call stack (g continues the program). If there's errors it will also stop and show them. You may be able to press g to ignore and continue.

 

Type lm to list loaded modules, x *!* to list the symbols and bp symbolname to set a breakpoint

F12           - break into program 
g             - continue 
p             - Step 
kb            - list call stack 
lm            - list loaded modules 
x *!*         - list all symbols 
ln <address>
- lists the nearest symbols to that address - used when you have a crash address 
bp symbolname - sets a breakpoint 
da <address>
- displays the ascii data found at that address 
dda <address>
- displays the value of the pointer 
dv            - display local variables 
kv 10         - displays last 10 stack frames 

-----------------------------------------------------------------
 
If programming in VB6 then this environmental variable link=/pdb:none stores the symbols in the dll rather than seperate files. Make sure you compile the program with No Optimisations and tick the box for Create Symbolic Debug Info. Both on the Compile tab in the Project's Properties.
 
Also CoClassSyms (microsoft.com/msj/0399/hood/hood0399.aspx) can make symbols from type libraries. 

-----------------------------------------------------------------

WinDbg can also analyse Blue Screen Crash Dumps (and indeed application crash dumps).

Dump Files
 
Dump files are files containing the state of the machine when it crashed. We can analyse the file to identify the driver (or program) causing the crash. See the last section on how to get them analysed by a volunteer.
 
Analyse Dump Files

If you want to analyse your own dump files.
 
You need to start Explorer as Administrator to access the files in C:\windows\Minidump. Right click Explorer and choose Run As Administrator.

Download and install Debugging Tools for Windows

 http://msdn.microsoft.com/en-us/windows/hardware/hh852363

Install theWindows SDK but just choose the debugging tools.

Create a folder called Symbols in C:\

Start Windbg. File menu - Symbol File Path and enter

 srv*C:\symbols*http://msdl.microsoft.com/download/symbols
 
Close and reopen WinDbg. File menu - Open Crash Dump

This will analyse the crash dump. You need to close and reopen WinDbg for each dump file analysed. Because you are downloading symbols from the internet WinDbg will appear to be doing nothing. But it's downloading. Be patient.
 
You are looking for a driver or system library that the crash occurred in at the end of the listing. Find the file, right click then Properties - Details tab. If it shows a driver you'll need to update the driver identified. Most drivers are in c:\windows\system32\drivers.
 

.

Tuesday 3 December 2019

Command Prompt Cheat Sheet

Informational Posts

Command Prompt Cheat Sheet

**CMD Cheat Sheet**

First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common.

**Getting Help**

For general help. Type `Help` in the command prompt. For each command listed type `help <command>` (eg `help dir`) or `<command> /?` (eg `dir /?`).

Some commands have sub commands. For example  `schtasks /create /?`.

The `NET` command's help is unusual. Typing `net use /?` is brief help. Type `net help use` for full help. The same applies at the root - `net /?` is also brief help, use `net help`.

References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.

--------------------------
**Punctuation**

    &    seperates commands on a line.
    
    &&    executes this command only if previous command's errorlevel is 0.
    
    ||    (not used above) executes this command only if previous command's 
    errorlevel is NOT 0
    
    >    output to a file
    
    >>    append output to a file
    
    <    input from a file
    
    2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)
    
    2>&1 Redirects command error output to the same location as command output. 
    
    |    output of one command into the input of another command
    
    ^    escapes any of the above, including itself, if needed to be passed 
    to a program
    
    "    parameters with spaces must be enclosed in quotes
    
    + used with copy to concatinate files. E.G. copy file1+file2 newfile
    
    , used with copy to indicate missing parameters. This updates the files 
    modified date. E.G. copy /b file1,,
    
    %variablename% a inbuilt or user set environmental variable
    
    !variablename! a user set environmental variable expanded at execution 
    time, turned with SelLocal EnableDelayedExpansion command
    
    %<number> (%1) the nth command line parameter passed to a batch file. %0 
    is the batchfile's name.
    
    %* (%*) the entire command line.
    
    %CMDCMDLINE% - expands to the original command line that invoked the
    Command Processor (from set /?).
    
    %<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. 
    Single % sign at command prompt and double % sign in a batch file.
    
    \\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.
    
    : (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.
    
    . (win.ini) the LAST dot in a file path separates the name from extension
    
    . (dir .\*.txt) the current directory
    
    .. (cd ..) the parent directory
    
    
    \\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off. 
    
    
    
    
    < > : " / \ | Reserved characters. May not be used in filenames.
    
    
    
    Reserved names. These refer to devices eg, 
    
    copy filename con 
    
    which copies a file to the console window.
    
    CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, 
    
    COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, 
    
    LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
    
    CONIN$, CONOUT$, CONERR$
    
    --------------------------------
    
    Maximum path length              260 characters
    Maximum path length (\\?\)      32,767 characters (approx - some rare characters use 2 characters of storage)
    Maximum filename length        255 characters

--------------------------------
**Starting a Program**


See start /? and call /? for help on all three ways.

There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows. 

If a full path isn't given then Windows looks in

 1. The directory from which the application loaded. 
    
 2. The current directory for the parent process. 
    
 3. Windows NT/2000/XP: The 32-bit Windows system directory. Use the
    GetSystemDirectory function to get the path of this directory. The
    name of this directory is System32. 
    
 4. Windows NT/2000/XP: The 16-bit Windows system directory. There is no
    function that obtains the path of this directory, but it is
    searched. The name of this directory is System. 
    
 5. The Windows directory. Use the GetWindowsDirectory function to get
    the path of this directory. 
    
 6. The directories that are listed in the PATH environment variable.

**Specify a program name**
--------------------------

This is the standard way to start a program.

    c:\windows\notepad.exe

In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.

If the program is a batch file control is transferred and the rest of the calling batch file is not executed.

**Use Start command**
--------------------------

`Start` starts programs in non standard ways.

    start "" c:\windows\notepad.exe

`Start` starts a program and does not wait. Console programs start in a new window. Using the `/b` switch forces console programs into the same window, which negates the main purpose of Start.

Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try 

    start shell:cache

Also program names registered under `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths` can also be typed without specifying a full path.

Also note the first set of quotes, if any, MUST be the window title.


**Use Call command**
-------------------------

Call is used to start batch files and wait for them to exit and continue the current batch file.


--------------------------------
**Keys**

**Ctrl + C** exits a program without exiting the console window.

For other editing keys type `Doskey /?`

Speaking Clock in VBScript.


'One file follows
'SpeakingClock.vbs
'Speaks the time continuously
Set speech = CreateObject("sapi.spvoice")
Do
If Hour(Now) < 12 then
Var = Hour(Now) & " AM"
else
Var = Hour(Now) - 12 & " PM"
End If

speech.Speak Var & " and " & Minute(Now) & " minutes and " & Second(Now) & " seconds"
wscript.sleep 5
Loop

Monday 2 December 2019

RunAsAdminConsole.exe eleates a existing console or runs a command leaving the console elevated. The program prompts for credentials.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
REM Three files follow
REM RunAsAdminConsole.bat
REM This file compiles RunAsAdminconsole.vb to RunAsAdminconsole.exe using the system VB.NET compiler.
REM Runs a command elevated using a manifest OR elevates the current console without parameters.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\RunAsAdminconsole.vb" /win32manifest:"%~dp0\RunAsAdmin.manifest" /out:"%~dp0\RunAsAdminConsole.exe" /target:exe
REM To use
rem RunAsAdminconsole 
pause



;RunAsAdminConsole.vb
imports System.Runtime.InteropServices 
Public Module MyApplication  
  
 Public Sub Main ()
  Dim wshshell as object
  WshShell = CreateObject("WScript.Shell")
  Shell("cmd /k " & Command())
 End Sub 

End Module 


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="1.0.0.0"
    processorArchitecture="*"
    name="Color Management"
    type="win32"
/>
<description>Serenity's Editor</description>
<trustinfo xmlns="urn:schemas-microsoft-com:asm.v2"> 
<security> 
    <requestedprivileges> 
        <requestedexecutionlevel level="requireAdministrator" uiAccess="false"/> 
    </requestedPrivileges> 
</security> 
</trustInfo> 

</assembly>

Thursday 28 November 2019

RunAsAdmin - Run a program elevated. The program prompts for credentials.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
REM Three files follow
REM RunAsAdminConsole.bat
REM This file compiles RunAsAdmin.vb to RunAsAdmin.exe using the system VB.NET compiler.
REM Runs a program elevated using a manifest
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\RunAsAdmin.vb" /win32manifest:"%~dp0\RunAsAdmin.manifest" /out:"%~dp0\RunAsAdmin.exe" /target:winexe
REM To use
REM     RunAsAdmin 
pause



'RunAsAdmin.vb
imports System.Runtime.InteropServices 
Public Module MyApplication  
 Public Sub Main ()
  Dim wshshell as object
  WshShell = CreateObject("WScript.Shell")
  WshShell.Run(Command())
 End Sub 
End Module 




RunAsAdmin.Manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="Color Management" type="win32" /> <description>Serenity's Editor</description> <trustinfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedprivileges> <requestedexecutionlevel level="requireAdministrator" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>

Tuesday 11 June 2019

ChangeWallpaper.exe - Changes the desktop wallpaper from the command line

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.

Although this is from the 2001 documentation and has been removed from current.


Setting pvParam to "" removes the wallpaper. Setting pvParam to VBNULL reverts to the default wallpaper.

See docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow

REM Compiles ChangeWallpaper.vb to ChangeWallpaper.exe
REM To use
REM ChangeWallpaper Wallpaper.bmp
REM EG ChangeWallpaper "C:\Windows\Web\Wallpaper\Theme1\img1.jpg"
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "ChangeWallpaper.vb" /out:"%~dp0\ChangeWallpaper.exe" /target:winexe
pause



;ChangeWallpaper.vb
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Public Module SendWinKey
    Public Declare Unicode Function SystemParametersInfoW Lib "user32" (ByVal uAction As Integer, ByVal uParam As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) As Integer
    Public Const SPI_SETDESKWALLPAPER = 20
    Public Const SPIF_SENDWININICHANGE = &H2
    Public Const SPIF_UPDATEINIFILE = &H1

Public Sub Main()    
    Dim Ret as Integer
    Dim FName As String
    'Takes a filename on the command line removing quotes
    FName = Replace(Command(), """", "")
    Ret = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, FName, SPIF_SENDWININICHANGE + SPIF_UPDATEINIFILE)
    If Ret = 0 Then Msgbox(err.lastdllerror)
End Sub

End Module

Friday 7 June 2019

Simulates the PrintScreen Key - SendKeys implemented in Windows Scripting and Basic languages cannot send PrintScreen key, this program allows the PrintScreen key to be simulated.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
REM Compiles PrintScreen.vb to PrintScreen.exe
REM SendKeys implemented in Windows Scripting and Basic languages cannot send PrintScreen key, this program allows the PrintScreen key to be simulated.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\PrintScreen.vb" /out:"%~dp0\PrintScreen.exe" /target:winexe
pause





Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Public Module SendWinKey
    Const KEYEVENTF_KEYDOWN As Integer = &H0
    Const KEYEVENTF_KEYUP As Integer = &H2

    Declare Sub keybd_event Lib "User32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As UInteger, ByVal dwExtraInfo As UInteger)

Public Sub Main()    
        keybd_event(CByte(Keys.PrintScreen), 0, KEYEVENTF_KEYDOWN, 0) 'press the PrintScreen key down
        keybd_event(CByte(Keys.PrintScreen), 0, KEYEVENTF_KEYUP, 0) 'release the PrintScreen key
End Sub

End Module

Monday 13 May 2019

ClearClipboard.exe clears any data on the Windows' clipboard

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
REM ClearClipboard.bat
REM This file compiles ClearClipboard.vb to ClearClipboard.exe using the system VB.NET compiler
REM ClearClipboard clears any data on the Windows' clipboard
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:winexe /out:"%~dp0\ClearClipboard.exe" "%~dp0\ClearClipboard.vb" 
pause



'ClearClipboard.vb
Imports System
Imports System.Windows.Forms.Clipboard
Public Module MyApplication  


 Sub Main()
  System.Windows.Forms.Clipboard.Clear()
 End Sub
End Module

Sunday 12 May 2019

ListAttr.exe lists all 19 of the attributes of a file, folder, volume, or device.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
@echo off
ECHO Three files follow
ECHO ListAttr.bat
ECHO This file compiles ListAttr.vb to ListAttr.exe using the system VB.NET compiler.
ECHO ListAttr.exe lists all 19 of the attributes of a file, folder, volume, or device.
Echo To Use
Echo         ListAttr ^
Echo -----------------------------------------------------------------------------------------
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\ListAttr.vb" /out:"%~dp0\ListAttr.exe" /target:exe
Pause



Echo ListAttrTest.Bat
"%~dp0\ListAttr" C:
"%~dp0\ListAttr" C:\
"%~dp0\ListAttr" C:\Windows\System32\Catroot
"%~dp0\ListAttr" nul
"%~dp0\ListAttr" c:\bootnxt
For /d %%A in ("C:\Windows\*") Do @"%~dp0\ListAttr" %%~A
Pause



'ListAttr.vb
imports System.Runtime.InteropServices 
Public Module MyApplication  

Public Declare Unicode Function GetFileAttributesW Lib "Kernel32" (ByVal Path As String) As Integer
Public Const FILE_ATTRIBUTE_ARCHIVE = 32 
Public Const FILE_ATTRIBUTE_COMPRESSED = 2048 
Public Const FILE_ATTRIBUTE_DEVICE = 64 
Public Const FILE_ATTRIBUTE_DIRECTORY = 16 
Public Const FILE_ATTRIBUTE_ENCRYPTED = 16384 
Public Const FILE_ATTRIBUTE_HIDDEN = 2 
Public Const FILE_ATTRIBUTE_INTEGRITY_STREAM = 32768 
Public Const FILE_ATTRIBUTE_NORMAL = 128 
Public Const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192 
Public Const FILE_ATTRIBUTE_NO_SCRUB_DATA = 131072 
Public Const FILE_ATTRIBUTE_OFFLINE = 4096 
Public Const FILE_ATTRIBUTE_READONLY = 1 
Public Const FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 4194304 
Public Const FILE_ATTRIBUTE_RECALL_ON_OPEN = 262144 
Public Const FILE_ATTRIBUTE_REPARSE_POINT = 1024 
Public Const FILE_ATTRIBUTE_SPARSE_FILE = 512 
Public Const FILE_ATTRIBUTE_SYSTEM = 4 
Public Const FILE_ATTRIBUTE_TEMPORARY = 256 
Public Const FILE_ATTRIBUTE_VIRTUAL = 65536 
  
Public Sub Main ()
 Dim Ret as Integer
 Dim OutPut As String
 Output = Command() & " - " & vbtab & vbtab
 Ret = GetFileAttributesW(Command())
 If Ret = -1 Then 
  Console.writeline("Error " & err.lastdllerror)
 Else
  If (Ret And FILE_ATTRIBUTE_ARCHIVE) = FILE_ATTRIBUTE_ARCHIVE Then Output = OutPut & "Archive "
  If (Ret And FILE_ATTRIBUTE_COMPRESSED) = FILE_ATTRIBUTE_COMPRESSED Then Output = OutPut & "Compressed "
  If (Ret And FILE_ATTRIBUTE_DEVICE) = FILE_ATTRIBUTE_DEVICE Then Output = OutPut & "Device "
  If (Ret And FILE_ATTRIBUTE_DIRECTORY) = FILE_ATTRIBUTE_DIRECTORY Then Output = OutPut & "Directory "
  If (Ret And FILE_ATTRIBUTE_ENCRYPTED) = FILE_ATTRIBUTE_ENCRYPTED Then Output = OutPut & "Encrypted "
  If (Ret And FILE_ATTRIBUTE_HIDDEN) = FILE_ATTRIBUTE_HIDDEN Then Output = OutPut & "Hidden "
  If (Ret And FILE_ATTRIBUTE_INTEGRITY_STREAM) = FILE_ATTRIBUTE_INTEGRITY_STREAM Then Output = OutPut & "Integrity_Stream "
  If (Ret And FILE_ATTRIBUTE_NORMAL) = FILE_ATTRIBUTE_NORMAL Then Output = OutPut & "Normal "
  If (Ret And FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) = FILE_ATTRIBUTE_NOT_CONTENT_INDEXED Then Output = OutPut & "Not_Content_Indexed "
  If (Ret And FILE_ATTRIBUTE_NO_SCRUB_DATA) = FILE_ATTRIBUTE_NO_SCRUB_DATA Then Output = OutPut & "No_Scrub_Data "
  If (Ret And FILE_ATTRIBUTE_READONLY) = FILE_ATTRIBUTE_READONLY Then Output = OutPut & "ReadOnly "
  If (Ret And FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS) = FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS Then Output = OutPut & "Recall_On_Data_Access "
  If (Ret And FILE_ATTRIBUTE_RECALL_ON_OPEN) = FILE_ATTRIBUTE_RECALL_ON_OPEN Then Output = OutPut & "Recall_On_Open "
  If (Ret And FILE_ATTRIBUTE_REPARSE_POINT) = FILE_ATTRIBUTE_REPARSE_POINT Then Output = OutPut & "Reparse "
  If (Ret And FILE_ATTRIBUTE_SPARSE_FILE) = FILE_ATTRIBUTE_SPARSE_FILE Then Output = OutPut & "Sparse "
  If (Ret And FILE_ATTRIBUTE_SYSTEM) = FILE_ATTRIBUTE_SYSTEM Then Output = OutPut & "System "
  If (Ret And FILE_ATTRIBUTE_TEMPORARY) = FILE_ATTRIBUTE_TEMPORARY Then Output = OutPut & "Temporary "
  If (Ret And FILE_ATTRIBUTE_VIRTUAL) = FILE_ATTRIBUTE_VIRTUAL Then Output = OutPut & "Virtual "
 End If
 Console.writeline(OutPut)
End Sub
End Module 

Saturday 11 May 2019

SetWindowText.exe sets the titlebar text for a window

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
Window Manipulation Posts

@Echo Off
Echo Two files follow
Echo SetWindowText.bat
Echo This file compiles SetWindowText.vb to SetWindowText.exe using the system VB.NET compiler.
Echo SetWindowText.exe sets the titlebar text for a window
Echo     SetWindowText.exe "OldWindowTitle" "NewWindowTitle"
Echo EG Open notepad and type in a command prompt
Echo     SetWindowText.exe "Untitled - Notepad" "My Window Title"
Echo ----------------------------------------------------------------------
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:winexe /out:"%~dp0\SetWindowText.exe" "%~dp0\SetWindowText.vb" 
pause



Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication  


Public Declare UNICODE Function FindWindowW Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr

Public Declare UNICODE Function SetWindowTextW Lib "user32" (ByVal hwnd As IntPtr, ByVal lpString As String) As Integer

Sub Main()
On Error Resume Next
Dim CmdLine As String
Dim Ret as Integer
Dim A() as String
Dim hwindows as IntPtr

CmdLine = Command()
If Left(CmdLine, 2) = "/?" Then
    MsgBox("Usage:" & vbCrLf & vbCrLf & "SetText ""OldWindowTitle"" ""NewWindowTitle""")
Else
    A = Split(CmdLine, Chr(34), -1, vbBinaryCompare)
    hwindows = FindWindowW(vbNullString, A(1))
    Ret = SetWindowTextW(hwindows, A(3))
End If
End Sub
End Module


Friday 10 May 2019

TopMost.exe set a window on top or not

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
Window Manipulation Posts

@Echo Off
Echo TopMost.bat
Echo This file compiles TopMost.vb to TopMost.exe
Echo TopMost.exe set a window on top or not
Echo To use 
Echo     TopMost Top ^
Echo     TopMost Not ^
Echo E.G.
Echo     TopMost Top Untitled - Notepad
Echo -----------------------------------------------------
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:winexe /out:"%~dp0\TopMost.exe" "%~dp0\TopMost.vb" 
pause



'TopMost.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module TopMost
 Public Declare UNICODE Function FindWindowW Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
 Public Declare Function SetWindowPos Lib "user32" (ByVal hwnd As IntPtr, ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer
 Public Const HWND_TOPMOST = -1
 Public Const SWP_NOMOVE = &H2
 Public Const SWP_NOSIZE = &H1
 Public Const HWND_NOTOPMOST = -2


 Sub Main()
  On Error Resume Next
  Dim hWindows as IntPtr
  Dim CmdLine as String
  Dim Ret as Integer
  CmdLine = Mid(Command(),5)
  hwindows = FindWindowW(vbNullString, CmdLine)
  If hwindows = 0 then
   Msgbox(Cmdline & " cannot be found.")
  Else
   If LCase(Left(Command(), 3)) = LCase("Top") then
    Ret = SetWindowPos(hwindows, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE)
    If Ret = 0 Then MsgBox("Set Pos Error is " & Err.LastDllError)
   ElseIf LCase(Left(Command(), 3)) = LCase("Not") then
    Ret = SetWindowPos(hwindows, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE)
    If Ret = 0 Then MsgBox("Set Pos Error is " & Err.LastDllError)
   Else
    Msgbox("Command line not recognised")
   End If
  End If
 End Sub
End Module

Thursday 9 May 2019

DeDup.exe Removes duplicate lines from StdIn and writes to StdOut

REM DeDup.bat
REM This file compiles DeDup.vb to DeDup.exe
REM DeDup.exe Removes duplicate lines from StdIn and writes to StdOut
REM To use
REM DeDup  < inputfile.txt > outputfile.txt
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\DeDup.exe" "%~dp0\DeDup.vb" /verbose
pause










'DeDup.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module DeDup
Sub Main
        Dim Dict as Object
        Dict = CreateObject("Scripting.Dictionary")
        Dim Line As Object
        Line=Console.readline
        Do Until Line = vbnull
                On Error Resume Next
                Dict.Add(Line, "")
                On Error Goto 0
                Line=Console.readline
        Loop


        For Each thing in Dict.Keys()
                Console.writeline(thing)
        Next
End Sub
End Module










Wednesday 8 May 2019

ListConsole.exe - similar to Unix's $SHLVL variable - list the processes in the current console and returns an errorlevel saying how many.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.

Similar to Unix's $SHLVL variable but adds ProcessIDs and command lines. List the processes in the current console and returns an ErrorLevel saying how many.




REM ListConsole.bat
REM This file compiles ListConsole.vb to ListConsole.exe
REM ListConsole.exe list the processes in the console and returns an errorlevel saying how many.
REM Similar to Unix's $SHLVL variable but adds ProcessIDs.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\ListConsole.vb" /out:"%~dp0\ListConsole.exe" /target:exe








---------------------------------------------------------------------------------






REM ListConsoleTest.bat
REM Shows ListConsole.exe in action.
cmd /c "%~dp0ListConsole.exe"
Echo Number of Processes is %errorlevel%
pause








-------------------------------------------------------------------------------





'ListConsole.vb
imports System.Runtime.InteropServices
Public Module MyApplication 

Public Declare Function GetConsoleProcessList Lib "Kernel32" (ByRef ProcessList as Integer, ByVal Count as Integer) As Integer
                
Public Sub Main ()
                Dim ProcessList(0 To 9) As Integer
                Dim Count As Integer
                Dim Ret As Integer
                Dim x as Integer
                Dim ColItems as Object
                Dim objWMIService As Object
                objWMIService = GetObject("winmgmts:\\.\root\cimv2")
                Count = 10
                'subtract one to account for this program
                Ret = GetConsoleProcessList(ProcessList(0), 10) - 1
                Console.Writeline("Level = " & Ret)

                For x = Ret  to 1 step -1
                    colItems = objWMIService.ExecQuery("Select * From Win32_Process where ProcessID=" & ProcessList(x))
                    For Each objItem in colItems
                        Console.writeline("PID : " & objItem.ProcessID & "  Command line : " &  objItem.CommandLine)
                    Next
                Next
                Environment.ExitCode = Ret         
End Sub
End Module



Tuesday 7 May 2019

ListEnvironment.exe List System, User, Volatile, and the resultant Process environmental variables that programs use.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
REM Two files follow
REM ListEnvironment.bat
REM This file compiles ListEnvironment.vb to ListEnvironment.exe using the system VB.NET compiler.
REM List System, User, Volatile, and the resultant Process environmental variables that programs use.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\ListEnvironment.vb" /out:"%~dp0\ListEnvironment.exe" /target:exe
REM To use
REM ListEnvironment
pause










-----------------------------------------------------------------------------------------




'ListEnvironment.vb
Imports System.Runtime.InteropServices
Public Module ListEnvironment
        Public Sub Main ()
                Dim WshShell As Object
                Dim wshsysEnv As ObJect
                Dim S As Object
                WshShell = CreateObject("WScript.Shell")

                wshsysEnv = WshShell.Environment("SYSTEM")
                console.writeline(vbCrLf & "--------")
                console.writeline("System")
                console.writeline("--------")
                For Each S In wshsysEnv
                    console.writeline(S)
                Next

                console.writeline(" ")
                wshsysEnv = WshShell.Environment("Volatile")
                console.writeline("--------")
                console.writeline("Volatile - These are set at logon")
                console.writeline("--------")
                For Each S In wshsysEnv
                    console.writeline(S)
                Next

                console.writeline(" ")
                wshsysEnv = WshShell.Environment("User")
                console.writeline("--------")
                console.writeline("User - These override system variables, and in the case of PATH are added to the system PATH")
                console.writeline("--------")
                For Each S In wshsysEnv
                    console.writeline(S)
                Next

                console.writeline(" ")
                wshsysEnv = WshShell.Environment("Process")
                console.writeline("--------")
                console.writeline("Process - This is the combined environment from the above for the program")
                console.writeline("          Variables starting with an equals sign, such as =C:=C:\Windows are internal CMD variables")
                console.writeline("          CMD simulates a default directory per drive like MSDos. This is how it keeps track")
                console.writeline("--------")
                For Each S In wshsysEnv
                    console.writeline(S)
                Next

                console.writeline(" ")
                console.writeline("--------")
                console.writeline("Dynamic - These are updated each time they are used")
                console.writeline("--------")
                console.writeline("CD")
                console.writeline("DATE")
                console.writeline("TIME")
                console.writeline("RANDOM")
                console.writeline("ERRORLEVEL")
                console.writeline("CMDEXTVERSION")
                console.writeline("CMDCMDLINE")
                console.writeline("HIGHESTNUMANODENUMBER")
        End Sub
End Module


PrintClip.exe prints any text or filenames on the clipboard to a StdOutn. Most programs cannot print filenames on the clipboard.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.

REM PrintClip.bat
REM This file compiles PrintClip.vb to PrintClip.exe
REM PrintClip.exe prints any text or filenames on the clipboard to a StdOut. Most programs cannot print filenames on the clipboard.
REM To use
REM PrintClip
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\PrintClip.exe" "%~dp0\PrintClip.vb" /verbose
pause








---------------------------------------------------------------------------------









'PrintClip.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module PrintClip
        Public Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Integer
        Public Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As IntPtr
        Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As IntPtr) As Integer
        Public Declare Function CloseClipboard Lib "user32" () As Integer
        Public Declare UNICODE Function DragQueryFileW Lib "shell32.dll" (ByVal HDROP As Integer, ByVal UINT As Integer, ByVal lpStr As String, ByVal ch As Integer) As Integer

        Public Const CF_TEXT = 1
        Public Const CF_BITMAP = 2
        Public Const CF_METAFILEPICT = 3
        Public Const CF_SYLK = 4
        Public Const CF_DIF = 5
        Public Const CF_TIFF = 6
        Public Const CF_OEMTEXT = 7
        Public Const CF_DIB = 8
        Public Const CF_PALETTE = 9
        Public Const CF_PENDATA = 10
        Public Const CF_RIFF = 11
        Public Const CF_WAVE = 12
        Public Const CF_UNICODETEXT = 13
        Public Const CF_ENHMETAFILE = 14
        Public Const CF_HDROP = 15
        Public Const CF_OWNERDISPLAY = &H80
        Public Const CF_DSPTEXT = &H81
        Public Const CF_DSPBITMAP = &H82
        Public Const CF_DSPMETAFILEPICT = &H83
        Public Const CF_DSPENHMETAFILE = &H8E


        Sub Main()
'                On Error Resume Next
                Dim Ret as IntPtr
                If OpenClipboard(0) <> 0 then
                        If IsClipboardFormatAvailable(CF_UNICODETEXT) <> 0 then
                                Ret = GetClipboardData( CF_UNICODETEXT)
                                Console.writeline(Marshal.PtrToStringUni(Ret))
                                Environment.ExitCode = 0
                        ElseIf IsClipboardFormatAvailable(CF_hDrop) <> 0 then
                                Dim TotalCount as Integer
                                Dim FName as String
                                Dim hDrop as IntPtr
                                hDrop = GetClipboardData( CF_hDrop)
                                FName = Space(33000)
                                TotalCount = DragQueryFileW(hDrop,  &hFFFFFFFF, FName, 33000)
                                For x = 0 to TotalCount - 1
                                        FName = Space(33000)
                                        If DragQueryFileW(hDrop,  x, FName, 33000) <> 0 then
                                                Console.writeline(Trim(FName))
                                        End If
                                Next
                                Environment.ExitCode = 0
                        Else
                                Environment.ExitCode = 1
                                Console.writeline("No text or filenames on clipboard")
                        End If
                        CloseClipboard()
                Else
                        Environment.ExitCode = err.lastdllerror
                        Console.Writeline("Clipboard is locked by another application")
                End If

        End Sub
End Module

Monday 6 May 2019

WinList.exe list the open windows and their child windows' Window Title, Window Class, and the EXE file

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
Window Manipulation Posts

REM WinList.bat
REM This file compiles WinList.vb to WinList.exe
REM WinList.exe list the open windows and their child windows' Window Title, Window Class, and the EXE file that created the window. 
REM To use type WinList in a command prompt
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\WinList.vb" /out:"%~dp0\WinList.exe" /target:exe
Pause
---------------------------------------------------------------------------------
'WinList.vb
imports System.Runtime.InteropServices 
Public Module WinList  

Public Declare Function GetTopWindow Lib "user32" (ByVal hwnd As IntPtr) As IntPtr
Public Declare Function GetWindow Lib "user32" (ByVal hwnd As IntPtr, ByVal wCmd As Integer) As IntPtr
Public Declare UNICODE Function GetWindowModuleFileNameW Lib "user32" (ByVal hwnd As IntPtr, ByVal WinModule As String, StringLength As Integer) As Integer
Public Declare UNICODE Function GetWindowTextW Lib "user32" (ByVal hwnd As IntPtr, ByVal lpString As String, ByVal cch As Integer) As Integer
Public Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As IntPtr, ByRef lpdwProcessId As IntPtr) As IntPtr
Public Declare UNICODE Function GetClassNameW Lib "user32" (ByVal hwnd As IntPtr, ByVal lpClassName As String, ByVal nMaxCount As Integer) As Integer
Public Declare Function IsWindowUnicode Lib "user32" (ByVal hwnd As IntPtr) As Boolean
Public Const GW_CHILD = 5
Public Const GW_HWNDNEXT = 2
  
Public Sub Main ()
 Dim WindowChain as Integer
     WindowChain = 0 
 Dim hwnd As IntPtr
 hwnd = GetTopWindow(0)
 If hwnd <> 0 Then
              AddChildWindows(hwnd, 0)
         End If
End Sub


Private Sub AddChildWindows(ByVal hwndParent As IntPtr, ByVal Level As Integer) 
 Dim objWMIService As Object
 Dim colItems As Object
 Dim TempStr As String 
 Dim WT As String, CN As String, Length As Integer, hwnd As IntPtr, TID As IntPtr, PID As IntPtr, MN As String, Parenthwnd As IntPtr
        Static Order As Integer
        Static FirstTime As Integer
        Parenthwnd = hwndParent
        If Level = 0 Then
                        hwnd = hwndParent
        Else
            hwnd = GetWindow(hwndParent, GW_CHILD)
        End If
        Do While hwnd <> 0
                 WT = Space(512)
                  Length = GetWindowTextW(hwnd, WT, 508)
                  WT = Left$(WT, Length)
                  If WT = "" Then WT = Chr(171) & "No Window Text" & Chr(187)
                  CN = Space(512)
                  Length = GetClassNameW(hwnd, CN, 508)
                  CN = Left$(CN, Length)
                  If CN = "" Then CN = "Error=" & Err.LastDllError
                  MN = ""
                  
                  TID = GetWindowThreadProcessId(hwnd, PID)
                  
 objWMIService = GetObject("winmgmts:\\.\root\cimv2")
 colItems = objWMIService.ExecQuery("Select * From Win32_Process where ProcessID=" & CStr(PID))
 For Each objItem in colItems 
  MN = objItem.name 
 Next                    
                Dim Unicode  as Boolean
 Unicode = IsWindowUnicode(hwnd)

                  Order = Order + 1
                If FirstTime = 0 Then
                    Console.writeline("Window Text                             " & "Class Name                       " & vbTab & "Unicode" & vbtab & "HWnd" & vbTab & "ParentHWnd" & vbTab & "ProcessID" & vbTab & "ThreadID" & vbTab & "Process Name" )
                    FirstTime = 1
                End If
 TempStr = vbCrLf & Space(Level * 3) & WT 
 If 30 - len(TempStr) > -1 then
  TempStr = TempStr & space(40 - len(TempStr))
 End If
 TempStr = TempStr & " " & CN 
 If 55 - len(TempStr) > -1 then
  TempStr = TempStr & space(75 - len(TempStr))
 End If
                Console.write(TempStr  & vbtab & Unicode & vbTab & CStr(hwnd) & vbTab & CStr(Parenthwnd) & vbTab & CStr(PID) & vbTab & CStr(TID) & vbTab & MN )
                 
                  AddChildWindows(hwnd, Level + 1)
                  hwnd = GetWindow(hwnd, GW_HWNDNEXT)
        Loop
      End Sub

End Module 

Tee.exe Reads from StdIn and writes to StdOut and a file.

REM Tee.bat
REM This file compiles Tee.vb to Tee.exe
REM Tee.exe Reads from StdIn and writes to StdOut and a file.
REM To use
REM    Tee Filename
Rem     Filename - name of file
Rem
Rem Example
Rem
Rem     tee "%userprofile%\Desktop\winini.txt" < "%windir%\win.ini"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\Tee.exe" "%~dp0\Tee.vb"
pause








-------------------------------------------------------------------------------------





'Tee.vb

Imports System

Imports System.IO

Imports System.Runtime.InteropServices

Imports Microsoft.Win32

 

Public Module Tee

Sub Main

        Dim Line as Object

        Dim FSO as Object

        Dim File as Object

        On Error Resume Next

        Fso = CreateObject("Scripting.FileSystemObject")

        File = Fso.CreateTextFile(Replace(Command(), """", ""), True)

        If err.number <> 0 then

                Console.WriteLine("Error: " & err.number & " " & err.description & " from " & err.source)

                err.clear

        Else

                Line=Console.readline

                Do Until Line = vbnull

                        File.Writeline(Line)

                        Console.WriteLine(Line)

                        Line = Console.ReadLine

                Loop

        End If

End Sub       

End Module

Sunday 5 May 2019

Cut.exe Removes specified lines from top or bottom of streams from StdIn and writes to StdOut.


REM Cut.bat
REM This file compiles Cut.vb to Cut.exe
REM Cut.exe Removes specified from top or bottom of lines from StdIn and writes to StdOut
REM To use
REM     cut {t|b} {i|x} NumOfLines
Rem Cuts the number of lines from the top or bottom of file.
Rem     t - top of the file
Rem     b - bottom of the file
Rem     i - include n lines
Rem     x - exclude n lines
Rem
Rem Example - Includes first 5 lines Win.ini
Rem
Rem     cut t i 5 < "%systemroot%\win.ini"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\Cut.exe" "%~dp0\Cut.vb"
pause


----------------------------------------------------------------------





'Cut.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module Cut
Sub Main
    Dim Arg() As Object
    Dim RS as Object
    Dim LineCount as Object
    Dim Line as Object
    Arg = Split(Command(), " ")
    rs = CreateObject("ADODB.Recordset")
    With rs
        .Fields.Append("LineNumber", 4)
        .Fields.Append("Txt", 201, 5000)
        .Open
        LineCount = 0
        Line=Console.readline
        Do Until Line = vbnull
            LineCount = LineCount + 1
            .AddNew
            .Fields("LineNumber").value = LineCount
            .Fields("Txt").value = Console.readline
            .UpDate
            Line = Console.ReadLine
        Loop

        .Sort = "LineNumber ASC"

        If LCase(Arg(0)) = "t" then
            If LCase(Arg(1)) = "i" then
                .filter = "LineNumber < " & LCase(Arg(2)) + 1
            ElseIf LCase(Arg(1)) = "x" then
                .filter = "LineNumber > " & LCase(Arg(2))
            End If
        ElseIf LCase(Arg(0)) = "b" then
            If LCase(Arg(1)) = "i" then
                .filter = "LineNumber > " & LineCount - LCase(Arg(2))
            ElseIf LCase(Arg(1)) = "x" then
                .filter = "LineNumber < " & LineCount - LCase(Arg(2)) + 1
            End If
        End If

        Do While not .EOF
            Console.writeline(.Fields("Txt").Value)
            .MoveNext
        Loop
    End With

End Sub   
End Module