Jump to content
Sign in to follow this  
Kealper

_WinAPI_SetConsoleTitle UDF (With detailed example!)

Recommended Posts

Kealper

Ok, so this has probably been posted before, but I was looking through the MSDN library randomly just a bit ago, and decided to play around a bit with some of the console-related functions.

AutoIt can make basic console applications to provide users with some basic output (which is generally more efficient than outputting to a GUI), but wouldn't it be cool to be able to name your console windows just like you can name your GUI windows?

Instead of it being called "C:\Users\Foobar\Desktop\MyEchoServer.exe" for instance, you could make your program call itself just "My Echo Server" and such.

Here is the simple UDF on it's own, and below this is a nice little example detailing how you can use the function.

; #FUNCTION# ====================================================================================================================
; Name ..........: _WinAPI_SetConsoleTitle
; Description ...: Change the AutoIt process's attached console title.
; Syntax ........: _WinAPI_SetConsoleTitle($sTitle[, $hDLL = "Kernel32.dll"])
; Parameters ....: $sTitle            - A string value.
;                 $hDLL             - [optional] A handle value. Default is "Kernel32.dll".
; Return values .: True if the title was able to be changed, False if it was not able to be changed.
; Author ........: Ken "Kealper" Piper
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _WinAPI_SetConsoleTitle($sTitle, $hDLL = "Kernel32.dll")
    Local $iRet = DllCall($hDLL, "bool", "SetConsoleTitle", "str", $sTitle)
    If $iRet[0] < 1 Then Return False
    Return True
EndFunc

And here is the example... For best results, save this to a file and compile it as a console application.

If it isn't compiled as a console application, there is a quick and dirty DllCall in there to create a "dummy" console if it doesn't exist already which can serve to demonstrate the function anyways (but without any textual output).

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

;Create a new console window if it does not already exist, even if it is not compiled as a console executable.
;This DllCall is not part of the example, it only serves to ensure the example works correctly.
;Don't run through SciTE, the example will fail, and even this DllCall can't fix that.
DllCall("Kernel32.dll", "bool", "AllocConsole") ;Don't just rely on this though, to get the most from this, compile as a console app!

;Begin actual example.

ConsoleWrite("Keep an eye on the console's window title!" & @CRLF)
Sleep(3000)

;First: Setting the title of your console window is as easy as this!
_WinAPI_SetConsoleTitle("This is some custom text!")

;A simple count-down, so the first title change is visible for a few seconds before proceeding to the next example.
For $i = 5 To 1 Step -1
    ConsoleWrite("Proceeding in " & $i & "..." & @CRLF)
    Sleep(1000)
Next
ConsoleWrite("On to example two! This'll count to 50 and then exit." & @CRLF)

;Second: Something a bit more advanced. Changing the console's title rapidly.
;When changing the console's title rapidly, you should first open Kernel32.dll and then pass that handle
;as a second parameter to the function. This makes it use the open handle instead of having to open and
;close Kernel32.dll each time the function is called. This ends up making it more efficient.
$Kernel32 = DllOpen("Kernel32.dll") ;Open Kernel32.dll. $Kernel32 now holds a handle to the opened file.
For $i = 1 To 50 ;Count to 50
    _WinAPI_SetConsoleTitle("Counting..." & $i, $Kernel32) ;Set the new title, and tell the function to use the open handle instead.
    Sleep(100) ;Wait 100ms, so the change can be easily seen by everyone. Without this, the change would happen too fast to notice.
Next
DllClose($Kernel32) ;Finally, because we like our resources, close the open handle since we no longer need it.


; #FUNCTION# ====================================================================================================================
; Name ..........: _WinAPI_SetConsoleTitle
; Description ...: Change the AutoIt process's attached console title.
; Syntax ........: _WinAPI_SetConsoleTitle($sTitle[, $hDLL = "Kernel32.dll"])
; Parameters ....: $sTitle            - A string value.
;                 $hDLL             - [optional] A handle value. Default is "Kernel32.dll".
; Return values .: True if the title was able to be changed, False if it was not able to be changed.
; Author ........: Ken "Kealper" Piper
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _WinAPI_SetConsoleTitle($sTitle, $hDLL = "Kernel32.dll")
    Local $iRet = DllCall($hDLL, "bool", "SetConsoleTitle", "str", $sTitle)
    If $iRet[0] < 1 Then Return False
    Return True
EndFunc
  • Like 3

Share this post


Link to post
Share on other sites
Kealper

Very good, this can be very useful!

Thanks for sharing.

Thanks for thanking! I don't post many code snippets on here, but it is nice to see that the ones I do post are appreciated ;)


Share this post


Link to post
Share on other sites
armoros

Very nice kealper...it will be handy for me.


[font="verdana, geneva, sans-serif"] [/font]

Share this post


Link to post
Share on other sites
UEZ

Look out for complete console implementation, e.g. by Mat, progandy, Shaggi, etc. ;)

Br,

UEZ


Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post


Link to post
Share on other sites
Kealper

Look out for complete console implementation, e.g. by Mat, progandy, Shaggi, etc. :)

This?

Me likey a lot ;)

I have to admit, that Console.au3 is something I fully intend on staring at the source to... My console reading function stopped working when AutoIt dropped the raw file read mode, since I was getting console text by reading the device file "con"... Thanks for pointing me in the direction of this!


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • ScriptJunky
      By ScriptJunky
      I noticed a lack of a constants file for _WinAPI_GetSystemMetrics() so I made this for anyone who wants to add it to their library. Enjoy!  (file attached below)
      #include-once ; #INDEX# ======================================================================================================================= ; Title .........: WinAPI GetSystemMetrics Constants ; AutoIt Version : 3.3.14.5 ; Language ......: English ; Description ...: Constants for _WinAPI_GetSystemMetrics(). ; Author(s) .....: ScriptJunky ; =============================================================================================================================== ; #CONSTANTS# =================================================================================================================== ; _WinAPI_GetSystemMetrics() Global Const $ARRANGE = 56 Global Const $CLEANBOOT = 67 Global Const $CMONITORS = 80 Global Const $CMOUSEBUTTONS = 43 Global Const $CONVERTIBLESLATEMODE = 0x2003 Global Const $CXBORDER = 5 Global Const $CXCURSOR = 13 Global Const $CXDLGFRAME = 7 Global Const $CXDOUBLECLK = 36 Global Const $CXDRAG = 68 Global Const $CXEDGE = 45 Global Const $CXFIXEDFRAME = 7 Global Const $CXFOCUSBORDER = 83 Global Const $CXFRAME = 32 Global Const $CXFULLSCREEN = 16 Global Const $CXHSCROLL = 21 Global Const $CXHTHUMB = 10 Global Const $CXICON = 11 Global Const $CXICONSPACING = 38 Global Const $CXMAXIMIZED = 61 Global Const $CXMAXTRACK = 59 Global Const $CXMENUCHECK = 71 Global Const $CXMENUSIZE = 54 Global Const $CXMIN = 28 Global Const $CXMINIMIZED = 57 Global Const $CXMINSPACING = 47 Global Const $CXMINTRACK = 34 Global Const $CXPADDEDBORDER = 92 Global Const $CXSCREEN = 0 Global Const $CXSIZE = 30 Global Const $CXSIZEFRAME = 32 Global Const $CXSMICON = 49 Global Const $CXSMSIZE = 52 Global Const $CXVIRTUALSCREEN = 78 Global Const $CXVSCROLL = 2 Global Const $CYBORDER = 6 Global Const $CYCAPTION = 4 Global Const $CYCURSOR = 14 Global Const $CYDLGFRAME = 8 Global Const $CYDOUBLECLK = 37 Global Const $CYDRAG = 69 Global Const $CYEDGE = 46 Global Const $CYFIXEDFRAME = 8 Global Const $CYFOCUSBORDER = 84 Global Const $CYFRAME = 33 Global Const $CYFULLSCREEN = 17 Global Const $CYHSCROLL = 3 Global Const $CYICON = 12 Global Const $CYICONSPACING = 39 Global Const $CYKANJIWINDOW = 18 Global Const $CYMAXIMIZED = 62 Global Const $CYMAXTRACK = 60 Global Const $CYMENU = 15 Global Const $CYMENUCHECK = 72 Global Const $CYMENUSIZE = 55 Global Const $CYMIN = 29 Global Const $CYMINIMIZED = 58 Global Const $CYMINSPACING = 48 Global Const $CYMINTRACK = 35 Global Const $CYSCREEN = 1 Global Const $CYSIZE = 31 Global Const $CYSIZEFRAME = 33 Global Const $CYSMCAPTION = 51 Global Const $CYSMICON = 50 Global Const $CYSMSIZE = 53 Global Const $CYVIRTUALSCREEN = 79 Global Const $CYVSCROLL = 20 Global Const $CYVTHUMB = 9 Global Const $DBCSENABLED = 42 Global Const $DEBUG = 22 Global Const $DIGITIZER = 94 Global Const $IMMENABLED = 82 Global Const $MAXIMUMTOUCHES = 95 Global Const $MEDIACENTER = 87 Global Const $MENUDROPALIGNMENT = 40 Global Const $MIDEASTENABLED = 74 Global Const $MOUSEPRESENT = 19 Global Const $MOUSEHORIZONTALWHEELPRESENT = 91 Global Const $MOUSEWHEELPRESENT = 75 Global Const $NETWORK = 63 Global Const $PENWINDOWS = 41 Global Const $REMOTECONTROL = 0x2001 Global Const $REMOTESESSION = 0x1000 Global Const $SAMEDISPLAYFORMAT = 81 Global Const $SECURE = 44 Global Const $SERVERR = 289 Global Const $SHOWSOUNDS = 70 Global Const $SHUTTINGDOWN = 0x2000 Global Const $SLOWMACHINE = 73 Global Const $STARTER = 88 Global Const $SWAPBUTTON = 23 Global Const $TABLETPC = 86 Global Const $XVIRTUALSCREEN = 76 Global Const $YVIRTUALSCREEN = 77  
      WinAPISystemMetricsConstants.au3
    • rcmaehl
      By rcmaehl
      A UDF with Extended Functions for Window Management
       
      Notes:
      Fixes WinGetClassList's barbaric returning of a @LF separated string instead of an array.
       
      Potential Uses:
      Automating applications that change their controls' handles/classes on each launch (e.g. half of Cisco's programs)
       
      Functions:
      _WinGetClassList
      _WinGetClassNNList
      _WindowGetHandleList
      _WindowGetHandleListFromPos
       
      Download: 
      WindowEx.zip  (v0.4)
       
      Changelog:
      10/04/2016 (v0.4): _WinGetClassNNList Fixed : Not Returning an Index when using $2D_ARRAY _WinGetClassNNList Fixed : Not Properly returning $aArray[x][1] on Classes with instances > 9 when using $2D_ARRAY 10/03/2016 (v0.3): _WinGetClassList Added : Exactly the same as WinGetClassList but returns a more civilized Array _WinGetClassNNList Added : Returns Classes and their instances in either a 1D or 2D array depending on Flags _WindowGetHandleList Renamed: _WinGetHandleList SCRIPT BREAKING! _WindowGetHandleListFromPos Renamed: _WinGetHandleListFromPos SCRIPT BREAKING! 10/01/2016 (v0.2): WindowsExConstants.au3 Added : Flags in _WindowGetHandleListFromPos _WindowGetHandleListFromPos Removed: ConsoleWrite left in during debug _WindowGetHandleListFromPos Added : Flag for if part of a Control is at $X, $Y return it as well. 10/01/2016 (v0.1): _WindowGetHandleList Added : Retrieves the handles of classes from a window. _WindowGetHandleListFromPos Added : Retrieves the handles of classes at a specific position from a window. Known and Reported Bugs:
      None reported To Do:
      To Be Decided. Opinions welcome! Upcoming Changes:
      To Be Decided.
    • chacoya121
      By chacoya121
      can someone plz explain how WinAPI work and some example script plz
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning everyone

      I was playing a little bit with "Screen Capture" UDF, and I was trying to make a "Window" capture, but, since I made a GUI which through I fire the event "Capture", my GUI is captured as well, and I don't want to
      This is the line of code that makes the capture:
       
      _ScreenCapture_CaptureWnd($strScreenCaptureFileName, $objActiveWindow, 0, 0, -1, -1, False) And these are the lines of code which select the "active" window:
       
      Local $objCurrentWindow = 9999 If _IsPressed("01") Then $objCurrentWindow = WinGetHandle("[ACTIVE]") If $objCurrentWindow <> $objMyGUI Then $objActiveWindow = $objCurrentWindow EndIf EndIf Sorry If I made stupid mistakes
      Thanks in advance.

      Francesco
×