Jump to content
Simpel

Free console after _WinAPI_AttachConsole()

Recommended Posts

Simpel

Hi.

Thanks to this post (https://www.autoitscript.com/forum/topic/189553-writing-to-cmd/?do=findComment&comment=1361142) I can now write a helpfile to the cmd when for instance passing parameter -h or -help at cmd. But then cmd is blocked by the script (I had to free it with CTRL+BREAK):

#include <WinAPI.au3>
_WinAPI_AttachConsole()
$hConsole = _WinAPI_GetStdHandle(1)
_WinAPI_WriteConsole($hConsole, "Print helpfile................" & @CRLF)

Inside MSDN Library then I found this sentence: A process can use the FreeConsole function to detach itself from its console.

But I don't find something like _WinAPI_FreeConsole(). How can I do it in another way?

Regards, Conrad


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites
spudw2k

Well, looking at the source code for the _WinAPI_AttachConsole in the WinAPI.au3 UDF and the FreeConsole MSDN page, I would think (unsure) it could be called using something like this:

Func _WinAPI_FreeConsole()
    Local $aResult = DllCall("kernel32.dll", "bool", "FreeConsole")
    If @error Then Return SetError(@error, @extended, False)
    Return $aResult[0]
EndFunc   ;==>_WinAPI_FreeConsole

It is curious that there isn't a function for this in the UDF.  Perhaps it is not essential...hopefully it works and fixes you issue.

Share this post


Link to post
Share on other sites
Simpel

Hi.

Inside my script $aResult[0]=1 so it means it works. But when I start test.exe (it should be compiled) from cmd.exe the caret is only just blinking further and not stopping output and showing promt including caret again:

#include <WinAPI.au3>

_WinAPI_AttachConsole()
Local $hConsole = _WinAPI_GetStdHandle(1)
_WinAPI_WriteConsole($hConsole, @CRLF & "Helpfile Line 1" & @CRLF)
_WinAPI_WriteConsole($hConsole, "Helpfile Line 2" & @CRLF)
_WinAPI_WriteConsole($hConsole, "Helpfile Line 3" & @CRLF)
_WinAPI_WriteConsole($hConsole, "Helpfile Line 4" & @CRLF)
Local $iSuccess = _WinAPI_FreeConsole()
MsgBox(0, 'FreeConsole', $iSuccess)
Exit

Func _WinAPI_FreeConsole() ; provided by spudw2k
    Local $aResult = DllCall("kernel32.dll", "bool", "FreeConsole")
    If @error Then Return SetError(@error, @extended, False)
    Return $aResult[0]
EndFunc   ;==>_WinAPI_FreeConsole

cmd looks like:

console not detached.PNG

cmd should look like:

should be like this.PNG

What am I missing?

At the end I want to write out a help file if someone is starting the test.exe with parameter h or help. And it should definitely give console free.

Regards, Conrad


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites
Earthshine

_WinAPI_DestroyWindow

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
Simpel

I don't want to shut the window. I just want to give the power over the cmd.exe back to system.


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites
Simpel

Even if closing the handle the cmd.exe isn't released:

#include <WinAPI.au3>
#include <Array.au3>

_WinAPI_AttachConsole()
Local $hConsole = _WinAPI_GetStdHandle(1) ; output
_WinAPI_WriteConsole($hConsole, @CRLF & "Helpfile Line 1" & @CRLF)
_WinAPI_WriteConsole($hConsole, "Helpfile Line 2" & @CRLF)
_WinAPI_WriteConsole($hConsole, "Helpfile Line 3" & @CRLF)
_WinAPI_WriteConsole($hConsole, "Helpfile Line 4" & @CRLF)
Local $iSuccess, $aSuccess
$aSuccess = DllCall("kernel32.dll","BOOL","CloseHandle","handle",$hConsole)
MsgBox(0, 'CloseHandle', $aSuccess[0])
$iSuccess = _WinAPI_FreeConsole()
MsgBox(0, 'FreeConsole', $iSuccess)
Exit

Func _WinAPI_FreeConsole() ; provided by spudw2k
    Local $aResult = DllCall("kernel32.dll", "bool", "FreeConsole")
    If @error Then Return SetError(@error, @extended, False)
    Return $aResult[0]
EndFunc   ;==>_WinAPI_FreeConsole

CloseHandle and FreeConsole both return 1 but I can't see the cmd prompt again except pressing Ctrl+Break.

Conrad


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites
spudw2k

Interesting...not sure the correct way to address this.  Doing some googling for the symptom brought up similar cases, but couldn't find a clear and applicable solution.  I assume you are going this route because you are making a hybrid GUI/console script?

Just a minor comment (not particularly useful), but I notice an Enter key also returns to the the prompt.  I would understand that if the process is being held or looping that a Ctrl + C or break would force close the app, but I can see the process terminate.  Not sure if there is another way to close the script to force a return to the prompt, but I couldn't find anything and it doesn't look like it's really "holding" anything.  I'm curious if someone else solves this in a proper manner.

Share this post


Link to post
Share on other sites
Simpel
11 minutes ago, spudw2k said:

I assume you are going this route because you are making a hybrid GUI/console script?

I’m facing this problem because I want to give an overview to the user about all possible arguments or parameters the GUI-script provides. Many of the tools I use will show such an overview if you start the prog in cmd.exe with argument -help.

I don’t like the idea showing a message box. Because you have to click ok and then all infos are gone. Other ideas?

Conrad


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites
jdelaney

You can always do what the windows management tools does, and launch a gui with all the parameters listed and defined...or write the help file to a .txt, and launch via notepad run command.

All my attempts to exit the attach failed as well, (unless compiled as a command line exe)

Edited by jdelaney

IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.

Share this post


Link to post
Share on other sites
spudw2k

@Simpel I agree with your position and approach, but I was wondering if you tried using the #AutoIt3Wrapper_Change2CUI=Y directive and the native ConsoleWrite function and if that wouldn't work for you.

I've used that method with some of my scripts--for example, my System Uptime script.  Admittedly though, none with GUI elements...but a quick test seemed to still allow GUI function and operation.

Edited by spudw2k

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

  • Similar Content

    • nacerbaaziz
      By nacerbaaziz
      Hi dear
      With this script you can print Unicode text in the CMD screen
      the script is  easy to use
      just you  write the text that contains Unicode in the first input
      and the script automatically reflect the code in the second input
       you can copy the text to the clipboard
      or you can try printing the text in the CMD window
      I apologize to everyone for colors and shape if not appropriate
      I'm a blind man and I do not see
      Thank you for your understanding
      Greetings to all of youCmdUtM.au3
    • TheAutomator
      By TheAutomator
      A fullscreen console with custom commands!

      Introduction:
      Hi everyone!
      This funny project started as a question in the help section:
      https://www.autoitscript.com/forum/topic/174404-edit-detect-key-before-updating-content/
      I'd like to share this script with everyone that is interested. 
       
      Why would I want it?
      You like the old style fullscreen console (like in the old day's), You can add custom commands, You can customize the font a lot more compared to cmd.exe, You can share ideas or add tweaks to the script.  
      Still to do:
      Write a simple custom programming language to implement this tool. Writing a little help file / pdf to describe my little programming language. Add little sound effects like a beep if there is a syntax error (optional). Clean up and modify Console.Au3 content. Add an option to have to type a login password (optional). Make an optional installer that also gives scripts for this tool a custom icon and open with command. ...Call Neo?  
      Thanks to:
      xxaviarxx: debugging, some ideas. jguinch: debugging, adding a bunch of tweaks and ideas. kylomas: debugging, new ideas.  
      Edits and updates:
      Added usage of tab key in edit control Edit has focus now on startup I'm currently rewriting a simple custom programming language to implement this tool.  
      UDF download: Console.au3
       
      Regards
      TheAutomator
    • hcI
      By hcI
      Hello I would like to know if there is a way to return a sentence in cmd when I launch from it (because I add arguments).
      For example, diskpart.exe which help to manage the key and hdd connected, when you launch it with the parameter "/f" the app return a sentence saying that it don't recognize the parameter "/f" and it return the sentence in the cmd where i started the application, not a new one.
      That's what I want to do but I couldn't find anything that would solve my problem on internet and on AutoIt like ConsoleWrite / ConsoleWriteError (don't work).
       
      Thanks
    • Duck
      By Duck
      I'm attempting to capture the output from the command line tool PSEXEC. I'm using AutoIT to run an instance of PSEXEC against a remote PC to audit Local Admins in my environment using net.exe (C:\Windows\System32> net localgroup administrators). However the usual trick I use to capture command line output does not appear to work well with PSEXEC, as the bottom portion of the output is missing from the return. Any ideas or recommendations are greatly appreciated.  
       
      Here is what I'm working with: 
      ;This script will read from a list of hosts and report who has local admin privileges on the machine #RequireAdmin Global $fileName = @ScriptDir & '\test.txt' ;hostlist, one host per line readHostList() ;Read list of hosts Func readHostList() Local $file = FileOpen($fileName, 0) While 1 $line = FileReadLine($file) If @error = -1 Then ExitLoop ConsoleWrite($line & @CRLF) ;MsgBox(0,0,$line) getLocalAdmins($line) WEnd FileClose($file) EndFunc ;run PSEXEC to list local admins Func getLocalAdmins($remotePC) Local $testFile = @ScriptDir &'\test234.txt' FileOpen($testFile, 1) Local $psexec = 'psexec \\' & $remotePC & ' net localgroup administrators' FileWriteLine($testFile, _RunCmd($psexec) ) FileClose($testFile) EndFunc ;Used to return CLI output Func _RunCmd($sCommand) Local $nPid = Run(@Comspec & " /c" & $sCommand, @SystemDir, @SW_Hide, 8), $sRet = "" If @Error then Return "ERROR:" & @ERROR ProcessWait($nPid) While 1 $sRet &= StdoutRead($nPID) If @error Or (Not ProcessExists ($nPid)) Then ExitLoop WEnd Return $sRet EndFunc  
      ## If i manually run the command on the remote PC via PSEXEC I will get the following output: 
      PsExec v2.11 - Execute processes remotely
      Copyright (C) 2001-2014 Mark Russinovich
      Sysinternals - www.sysinternals.com
      Starting net on PCNAME... on PCNAME...
      net exited on PCNAME with error code 0.
      -------------------------------------------------------------------------------
      admin
      Administrator
      Alias name     administrators
      Domain\Domain Admins
      Comment        Administrators have complete and unrestricted access to the computer/domain
      Members
      The command completed successfully.
       
      ## The returned output from running the above script is as follows:
      PsExec v2.11 - Execute processes remotely
      Copyright (C) 2001-2014 Mark Russinovich
      Sysinternals - www.sysinternals.com
      Alias name     administrators
      Connecting to PCNAME...
      Starting PSEXESVC service on PCNAME...
      Connecting with PsExec service on PCName...
      Starting net on PCNAME..
      net exited on PCNAME with error code 0.
       
      **Note to test this script PSEXEC must be in the system dir or the path in the script changed 
      PSEXEC tool: https://docs.microsoft.com/en-us/sysinternals/downloads/psexec
    • luckyluke
      By luckyluke
      Hello,
      Im trying to read the output from CMD using Dllcall, here is my code:
      #include <WinAPI.au3> #include <array.au3> Global Const $STD_OUTPUT_HANDLE = -11 Global Const $_CONSOLE_SCREEN_BUFFER_INFO = _ "struct;int dwSizeX;" & _ "short dwSizeY;" & _ "short dwCursorPositionX;" & _ "short dwCursorPositionY;" & _ "short wAttributes;" & _ "short Left;" & _ "short Top;" & _ "short Right;" & _ "short Bottom;" & _ "short dwMaximumWindowSizeX;" & _ "short dwMaximumWindowSizeY;endstruct" $pCmd = Run( "cmd.exe" ) Sleep(1000) $hCmd = WinGetHandle("") ConsoleWrite('handle:' & $hCmd & @CRLF) $aRet = DllCall("kernel32.dll", "int", "AttachConsole", "dword", $pCmd) ;_ArrayDisplay($aRet) If $aRet[0] <> 0 Then $vHandle_data='' $vHandle='' $vHandle_data = DllStructCreate($_CONSOLE_SCREEN_BUFFER_INFO) ; Screen Buffer structure $aRet1 = DllCall("kernel32.dll", "hwnd", "GetStdHandle", "dword", $STD_OUTPUT_HANDLE) if not @error Then $vHandle = $aRet1[0] $aRet = DllCall("kernel32.dll", "int", "GetConsoleScreenBufferInfo", "hwnd", $vHandle, _ "ptr", $vHandle_data) MsgBox(0, '1',DllStructGetData($vHandle_data, 'dwSizeX') & _WinAPI_GetLastErrorMessage()) EndIf It did not work, i got the message 'The handle is invalid'. Please help?
      Thank you in advance!
×