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

    • MFrancisca
      By MFrancisca
      Hello! 
      I've been checking the logging UDFs in the wiki, mostly Log4a and Loga and I wanted to ask which one would you recommend for a script that will be executed remotely through PSExec. My main question is where the logs are located in that situation and if I can change that location to a custom one., because I need to retrieve them at the end of execution.
      So in a rough description the process is
      Open PSExec
      Send compiled AutoIT script to remote machine
      Execute script
      Copy logs from the remote to the local machine.
       
      Any opinions? 
    • VADemon
      By VADemon
      I've encountered a problem with a single file where I cannot retrieve it's Date-time. So far my code has worked well for over 30 files, but this one is a mystery I cannot debug myself due to insufficient Au3 knowledge.
      In line 11 "_Date_Time_FileTimeToArray" is called and for this particular file it sets the @error to 10. I don't know what that error code means, but it's not set by the _Date functions themselves I think.
      Overall, it could be a problem caused by any of the functions below, how can I properly debug this? / Does anybody know a what's causing this?
      _WinAPI_CreateFile() / _Date_Time_GetFileTime() / _Date_Time_FileTimeToArray()
      Func _SetFileTimes($sFilePath) Local $monthNumber[13] = ["", "January", "February", "March", "April", "May", "Juny", "July", "August", "September", "October", "November", "December"] Local $dayNumber[7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] Local $fHandle = _WinAPI_CreateFile($sFilePath, 2, 2) ; read-only ; may NOT return a valid date for some reason! TODO Local $fTagFILETIME = _Date_Time_GetFileTime($fHandle) _WinAPI_CloseHandle($fHandle) ; This will return an empty array if theres no valid date $fModTime = _Date_Time_FileTimeToArray($fTagFILETIME[2]) ; last Modified if @error <> 10 then Local $year = $fModTime[2] Local $month = $fModTime[0] Local $day = $fModTime[1] Local $hour = $fModTime[3] Local $min = $fModTime[4] Local $sec = $fModTime[5] Local $ms = $fModTime[6] Local $weekday = $fModTime[7] Global $prettyTimestamp = StringFormat("%s, %s %d, %04d %02d:%02d:%02d", $dayNumber[$weekday], $monthNumber[$month], $day, $year, $hour, $min, $sec) Global $uploadDate = StringFormat("%04d-%02d-%02d", $year, $month, $day) $fModTime = _Date_Time_FileTimeToArray(_Date_Time_FileTimeToLocalFileTime($fTagFILETIME[2])) ; last Modified Local $year = $fModTime[2] Local $month = $fModTime[0] Local $day = $fModTime[1] Local $hour = $fModTime[3] Local $min = $fModTime[4] Local $sec = $fModTime[5] Local $ms = $fModTime[6] Local $weekday = $fModTime[7] ; GetUnixTime accounts for Local time, hence feed it local time Global $unixTimestamp = _GetUnixTime($year &"/"& $month &"/"& $day &" "& $hour&":"& $min &":"& $sec) else Global $prettyTimestamp = "N/A" Global $uploadDate = "" Global $unixTimestamp = "N/A" endif endfunc  
      _GetUnixTime returned the year 1601 start date, showing that $fModTime is probably equal 0. (But Why?)
      The file reports these dates in Explorer, it's on local NTFS drive:
      Created: ‎‎Wednesday, ‎31. ‎Januar ‎2018, ‏‎18:55:02
      Modified: ‎Wednesday, ‎10. ‎Januar ‎2018, ‏‎12:39:23
      Accessed: ‎Wednesday, ‎10. ‎Januar ‎2018, ‏‎12:39:23
    • caramen
      By caramen
      I watched _OL_ItemSend&_OL_ItemFind&_OL_ItemCreate in OutlookEx UDF but hmmm
       
      Since it use the test environnement i cant get the orders of the mail creation
       
      Can someone make me win some time of reading all exemples script and lead me how to do one ?
      That whould be lovely.
      Gnight
    • FMS
      By FMS
      Hello,

      I'm having a problem whit winwait on firefoxscreens whit the same title and text.
      On mine quest on this forum and internet I've found some work around and solutions.
      unfortunaly This wasn't working for me.

      I've tried searching tru winlist or finding some unique text but wasn't finding any solution.
      Does anyone know how to get the wright handle?
      I just want to move the browser to the right place in the end whit WinMove.

      thnx in advanced.

       
      #include <Array.au3> Global $A_URL[4][2] = _ [["url1" , "same_title"] , _ ["url2", "same_title"] , _ ["url3" , "other_title" ] , _ ["url4" , "other_title" ]] ;~ _ArrayDisplay($A_URL) ;-----kill all firefox.exe ;~ Run("taskkill /IM firefox.exe /F", "", @SW_HIDE) ;Sleep(5000) For $i = 0 To 1 ConsoleWrite("running 1 : " & $i & @CRLF) Local $ID = ShellExecute("firefox.exe", "-new-window " & $A_URL[$i][0] ,"C:\Program Files\Mozilla Firefox" ) ConsoleWrite("$ID = " & $ID & @CRLF) Next sleep(200) ;~ Local $screen1HWND = WinWait($A_URL[0][1],"") ;~ If Not WinActive($screen1HWND) Then WinActivate($screen1HWND) ;~ ConsoleWrite("$screen1HWND = " & $screen1HWND & @CRLF) ;~ Local $screen2HWND = WinWait($A_URL[1][1],"") ;~ If Not WinActive($screen2HWND) Then WinActivate($screen2HWND) ;~ ConsoleWrite("$screen2HWND = " & $screen2HWND & @CRLF) $sWinTitle = $A_URL[0][1] $avWinList = WinList($sWinTitle) For $n = 1 to $avWinList[0][0] ConsoleWrite("Window " & $n & ": Text: " & WinGetText($avWinList[$n][1]) & @LF) Next For $i = 0 To 1 ;~ WinWait("title1", "", 10) ;~ WinActive("title1", "") ;~ WinMove ("title1", "", $i , $i ) Next  
    • Tersion
      By Tersion
      Here the this wiki page with list of available UDFs for data compression. For my tasks I only need ZIP support, so I started looking at pure AutoIt UDFs without any 3rd party dlls. And found out that most of available realizations uses standard ("native method") Windows dll - "zipfldr.dll". So for now I chose ZIP UDF by wraithdu. I've tested it on Windows 7 (x64) and it seem works fine. But here the comment from another topic where user says that Windows 10 discontinued support of "zipfldr.dll". Now I confused. I don't have around any Windows 10 machine to tested it. So maybe someone could confirm or deny that? Or maybe would better to switch to UDF with 7zip dll?
      I need an advice...
×