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

    • badcoder123
      By badcoder123
      I was looking around the help file and I came across _GDIPlus_GraphicsDrawRect and _WinAPI_DrawLine and I seem to be having the same "problem" where every time it draws into a window and you lose or gain focus it has to redraw itself. Is there anyway around this? 
      #include <WindowsConstants.au3> #include <WinAPI.au3> #Include <GDIPlus.au3> _GDIPlus_Startup() Run("notepad.exe") $hWnd = WinWait("Untitled") $hGraphic = _GDIPlus_GraphicsCreateFromHWND($hWnd) $Color = 0xFFFF0000 $hPen = _GDIPlus_PenCreate($Color, 2) For $i = 1 To 10 _GDIPlus_GraphicsDrawRect($hGraphic, 200, 200, 25 ,25, $hPen) ToolTip($i) Sleep(1000) Next _WinAPI_RedrawWindow($hWnd, 0, 0, $RDW_INVALIDATE + $RDW_ALLCHILDREN) _GDIPlus_GraphicsDispose($hGraphic) _GDIPlus_PenDispose($hPen) _GDIPlus_Shutdown()  
    • TheSaint
      By TheSaint
      Here is the bare bones of a UDF I have started work on.
      Mostly just a proof of concept at this stage, and still need to add some functions and dress the UDF up a bit ... to look like a UDF ... though it has my own distinct styling, especially as I have never really developed a UDF before now .... used plenty and modified plenty though. I've even invented my own UDF variable naming convention, which I am sure some of you will be aghast at. I work with what feels best for me, but others are free to adapt if they wish.
      The idea is to emulate the simplicity of INI files, but gain the benefits of SQL.
      Two scripts are provided.
      (1) The UDF, a work in progress - SimpleSQL_UDF.au3
      (2) An example or testing script - UDF_Test.au3
      Another first for me, is creating a 2D array from scratch, never done that before, that I can recall ... never had a need, and even for 1 dimension arrays, for a long time now, I have just used _StringSplit to create them. So I needed a bit of a refresher course, which my good buddy @TheDcoder assisted me with ... not without some angst I might add. LOL
      SimpleSQL_UDF.zip
      Program requires the sqlite3.dll, not included, but easily enough obtained.
      Hopefully the usage is self-evident ... just change the Job number variable in the UDF_Test.au3 file to check the existing functions out.
      Enjoy!
      P.S. This is also related to a new program I have just finished and uploaded - INItoSQL DB
    • xtcislove
      By xtcislove
      Hello,
      as a start in Autoit i tried something i was missing since im using Autoit. 

      I build a custom MessageBox which has a large amount of custom options and which scales its size on the parameters you set. 

      Aviable Settings:
      -Title
      -Unlimited Buttons
      -Text Color (Buttons, Text)

      -Background Color (Msgbox, Buttons, Label) 

      -Button Timeout
      -Autoclose Timeout
      -Icon (Default, No Icon, Custom)

      -Label/ Button Style. 
      -Transparency

      I tried to keep this as close as i could to a Msgbox i was used too on my batch times.

      After i was ready i realised, @Melba23 probably build a way better msgbox which would have suit my needs enterly, anyway thanks to @Melba23 because i use his Stringsize UDF. 

       
       
      local $Message = _sMsgBox("Test", 6, "Continue?") if @extended <> -1 Then MsgBox(0, @extended, $Message&" Button pressed")  
      ScalingMessageBox.au3
    • Gowrisankar
      By Gowrisankar
      Dear members, 
      I am working on a project where, emails from outlook are to be read and moved to various folders within the mailbox, based on the content of the emails.
      I used the below code for moving mails. It works fine when I run it against individual mail ids. But when I run it on Shared mailbox, the mails are not moved to respective folders.
      _OL_ItemMove($oOutlook, $sEntryId, Default, $sDestinationFolder) The value of $sEntryId is saved in an excel report initially. The current process reads the $sEntryId from the excel and passes it to "_OL_ItemMove" statement.
      Requesting the guidance of the forum members in this issue.
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening everyone
      I am working with Word UDF ( thanks @water! ), and, especially, with the function _Word_DocFindReplace().
      The replace does work everywhere in the document, but, it does not work in Headers or Footers.
      Am I missing something or am I forced to use the code below?
      I have already looked in the Help file ( about _Word_DocFindReplace() ), but there are no mentions about replace text in Headers/Footers.
      Sub FindAndReplaceFirstStoryOfEachType() Dim rngStory As Range For Each rngStory In ActiveDocument.StoryRanges With rngStory.Find .Text = "find text" .Replacement.Text = "I'm found .Wrap = wdFindContinue .Execute Replace:=wdReplaceAll End With Next rngStory End Sub Thanks everyone in advance


      Best Regards.
×