- Window. Hide Метод
- Определение
- Исключения
- Комментарии
- Hide empty console window in a all GUI Powershell script?
- 5 Answers 5
- Not the answer you’re looking for? Browse other questions tagged winforms powershell or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Hide command prompt window when using Exec()
- 8 Answers 8
- How can I run a windows batch file but hide the command window?
- 10 Answers 10
- 10 Ways To Run Batch Files Silently And Hide The Console Window
- Run a Silent Batch Script Using a Third Party Utility
- Hide the Batch Console With a Visual Basic Script
Window. Hide Метод
Определение
Делает окно невидимым. Makes a window invisible.
Исключения
Метод Hide() вызывается для окна, которое закрывается (Closing) или закрыто (Closed). Hide() is called on a window that is closing (Closing) or has been closed (Closed).
Комментарии
Окно не закрывается, когда оно скрыто, и не возникает ни одно Closing Closed событие или. A window is not closed when it is hidden, and neither the Closing nor Closed event is raised. Вместо этого свойству окна присваивается Visibility значение Visibility.Hidden . Instead, the window’s Visibility property is set to Visibility.Hidden.
Если окно является приложением MainWindow , а приложение ShutdownMode — OnMainWindowClose , приложение не завершит работу. If a window is the application’s MainWindow and the application’s ShutdownMode is OnMainWindowClose, the application does not shut down. Аналогичным образом приложение не завершает работу, если окно является единственным окном, а режим завершения работы приложения — OnLastWindowClose . Likewise, the application does not shut down if a window is the only window and the application’s shutdown mode is OnLastWindowClose.
Если вы хотите отображать и скрывать окно несколько раз в течение всего времени существования приложения и вы не хотите повторно создавать экземпляр окна при каждом его отображении, можно обойти Closing событие, отменить его и вызвать Hide метод. If you want to show and hide a window multiple times during the lifetime of an application, and you don’t want to re-instantiate the window each time you show it, you can handle the Closing event, cancel it, and call the Hide method. Затем можно вызвать в Show том же экземпляре, чтобы снова открыть его. Then, you can call Show on the same instance to re-open it.
Hide empty console window in a all GUI Powershell script?
I have made a very simple Powershell script with WinForms GUI. Everything works as intended but, when I run the .ps1 script with PowerShell a black empty console window appears at first and then the GUI shows.
Anyway to make the console window dissapear?
5 Answers 5
I wrote a small article on this subject (sorry in french) one year ago.
Here is the common solution using a small VBS script to start PowerShell hidding his window (the trick is in the last ,0).
I also embeded PowerShell in an executable with no console called slxPShell2.EXE.
I found the above didn’t work for me. I used this:
Hope that helps.
This solution Minimizes Powershell window after it starts. Powershell window opens, then disapears, without using any outside code. Put at beginning of your script.
This is how I got this working:
- Have the Winforms GUI script in one ScriptOne.ps1 file
- Create another LaunchScriptOne.ps1 file with the content:
powershell.exe -WindowStyle Hidden -File «C:\path\to\ScriptOne.ps1» .
The solution was provided in another thread on the same topic: Hide or Minimize the powershell prompt after Winform Launch
I hope someone will find a way to put this into one single script as well. The answers above in this thread did not help me, but maybe I did something wrong, idk.
I’m nube so no rep so can’t comment inline. though wrt @Ipse’s solution which I’m a fan of, I also make sure to close the hidden window when the script is done. not sure if PS gets around to this sort of auto-garbage collection, but suspect it’s good best practice.
eg. at end of your script I’d suggest doing:
stop-process -Id $PID
(which should terminate that hidden window v. just leave it lurking around and tying up those resources).
Not the answer you’re looking for? Browse other questions tagged winforms powershell or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Hide command prompt window when using Exec()
I’m trying to execute this simple test script, but a command shell window is appearing after I execute the script.:
How can I prevent it from showing up?
Update
I was able to improve it with this code change:
Now the window only shows up for a split second. But I don’t want it to show up at all.
8 Answers 8
You’re always going to get a window flash with Exec() . You can use Run() instead to execute the command in a hidden window. But you can’t directly capture the command’s output with Run() . You’d have to redirect the output to a temporary file that your VBScript could then open, read, and delete.
The FileSystemObject class has methods like GetSpecialFolder() to retrieve the path of Windows temp folder and GetTempName() to generate a temporary filename that you can use instead of hardcoding an output filename as I’ve done above.
Also note that you can use the /FO CSV argument with tasklist.exe to create a CSV file which should make parsing it much easier.
Finally, there are VBScript «native» ways to retrieve the list of running processes. WMI’s Win32_Process class, for example, can do this without the need for Run/Exec .
Edit:
For the sake of completeness, I should mention that your script can relaunch itself in a hidden console window where you can run Exec() silently. Unfortunately, this hidden console window will also hide your output from functions like WScript.Echo() . Aside from that, however, you probably won’t notice any differences running your script under cscript vs wscript . Here’s an example of this method:
Of course, if your script expects command-line parameters, those would need to be forwarded when relaunching your script as well.
How can I run a windows batch file but hide the command window?
How can I run a windows batch file but hiding the command window? I dont want cmd.exe to be visible on screen when the file is being executed. Is this possible?
10 Answers 10
If you write an unmanaged program and use CreateProcess API then you should initialize lpStartupInfo parameter of the type STARTUPINFO so that wShowWindow field of the struct is SW_HIDE and not forget to use STARTF_USESHOWWINDOW flag in the dwFlags field of STARTUPINFO. Another method is to use CREATE_NO_WINDOW flag of dwCreationFlags parameter. The same trick work also with ShellExecute and ShellExecuteEx functions.
If you write a managed application you should follows advices from http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx: initialize ProcessStartInfo with CreateNoWindow = true and UseShellExecute = false and then use as a parameter of . Exactly like in case of you can set property WindowStyle of ProcessStartInfo to ProcessWindowStyle.Hidden instead or together with CreateNoWindow = true .
You can use a VBS script which you start with wcsript.exe. Inside the script you can use CreateObject(«WScript.Shell») and then Run with 0 as the second ( intWindowStyle ) parameter. See http://www.robvanderwoude.com/files/runnhide_vbs.txt as an example. I can continue with Kix, PowerShell and so on.
If you don’t want to write any program you can use any existing utility like CMDOW /RUN /HID «c:\SomeDir\MyBatch.cmd», hstart /NOWINDOW /D=c:\scripts «c:\scripts\mybatch.bat», hstart /NOCONSOLE «batch_file_1.bat» which do exactly the same. I am sure that you will find much more such kind of free utilities.
In some scenario (for example starting from UNC path) it is important to set also a working directory to some local path ( %SystemRoot%\system32 work always). This can be important for usage any from above listed variants of starting hidden batch.
10 Ways To Run Batch Files Silently And Hide The Console Window
Most ordinary Windows users never use the Command Prompt and have no idea what sort of things you can do from the command line. More experienced users will know that running command line commands can be very useful for a range of tasks and grouping everything into a single batch file to process it all together can be very powerful.
One inconvenience with running batch files is that they always open a console window which shows the output of the commands being executed. This can be important if you want to interact or see what is happening while the batch file is running but a bit annoying if you want to run the batch script quietly in the background or while starting windows.
For short batch files, the console window may appear and disappear in a flash or stay open for longer if more commands are being executed. There is no standard built in way to completely hide the console window from showing so if you want to do that another solution is required. Here we show you some different ways to make your batch script run silently without a console window showing.
Run a Silent Batch Script Using a Third Party Utility
A simple and common solution for running a batch file silently is launching it via a third party utility that suppresses the console window.
Hidden Start (HStart)
Hidden Start is a portable and quite powerful tool that can launch executables and scripts with several useful options. We are using version 4.2 from 2013 because it’s portable and not as restricted as newer versions. Since version 4.3, Hidden Start is no longer portable and also pops up a nag every time you try to run a hidden console, which makes it useless for this purpose.
Unzip and run the program with HStartUI.exe, the process consists of three steps. Manually add or drop your batch file onto the window, make sure “Hide console window” is checked and optionally check “Run with highest privileges” if your script requires it. Other setup options like priority or starting directory are not essential unless you know the script requires them.
Step 3 shows the output command that has to be manually run. You can use the buttons at the bottom to copy the command, automatically create a shortcut or add an autostart entry into the registry. Note the bypass UAC prompt option is not available in the free version (we show you how to do that for free later).
SilentCMD
This is a small 14KB tool that is not blessed with tons of features but does the simple task which we are looking for. If you are on Windows 10, .NET Framework 3.5 will be offered for install when running the tool if it isn’t already on your system. The basic syntax to use in shortcuts or similar is quite simple.
SilentCMD [path to .bat file] [batch arguments] [options]
There are two additional options in SilentCMD. One is to enable logging with “/log:[path to .txt]” and the other is to start the script after a delay using “/DELAY:[xx seconds]”. Append the option to the end of the command. As long as you don’t need extra functions like elevation or a different starting directory, SilentCMD works nicely and might be all that you need.
NirCMD
Nirsoft’s NirCMD is a small multi function tool that can quietly perform dozens of tasks without popping up any console window. These include ejecting ROM drives, changing audio volumes, enabling screensavers, controlling processes/services and much more. The following command can be used at boot or in a shortcut to run a batch file silently:
nircmd exec hide [path to .bat file]
The exec and hide commands are used to execute the script and hide any console windows from opening.
Include elevatecmd to request administrator privileges for the batch file although it’s only needed if you know commands in your script require elevation.
nircmd elevatecmd exec hide [path to .bat file]
A desktop shortcut can be created manually or you can tell NirCMD to create a shortcut from the command line with the included commands so the silent script is ready to run.
$folder.desktop$” “SilentBatch” exec hide C:\Users\Raymondcc\MyBatchFile.bat
The above will create a desktop shortcut called SilentBatch which will silently execute the MyBatchFile.bat script. Note that you may have to change the “Start in” location in the shortcut as output from the script that doesn’t supply a path will default to C:\Windows.
On double clicking the NirCMD executable it will offer the option to copy itself to the Windows directory so you only have to use nircmd.exe and not supply a full path every time. It’s advisable to do that if you plan to make use of NirCMD on your computer (make sure to right click and run nircmd.exe as administrator).
For full information about the wealth of commands available, have a read of the full NirCMD Help file.
Raymond.cc Silent Batch Launcher
We also have a little tool that can launch a batch file silently. It’s created in Autoit and is essentially a slightly advanced version of the “Create Your Own Executable File” method on page two. Silent Batch Launcher is designed to be simple to use and provide a slightly different option to the other tools here.
Run the executable and you will be asked to browse for a batch file. An INI file containing the path to the script will then be created next to the executable. Every time you run Silent Batch Launcher from then on it will execute the same batch file as long as the INI file is present.
To run a different script, delete the INI file or hold Shift while launching the tool and it will popup the file requester. The INI file name will match the EXE file name so you can have differently named occurrences of the tool in the same folder. There are two files in the archive, use the “Admin” version if the script requires elevation. Any useful feedback you have about the tool is welcome.
Note: Because this tool was created with Autoit, it does create some false positives with online virus scanners like VirusTotal.
There are a few other tools that can hide the console window of a batch script that we haven’t mentioned here. They include Cmdow, Create Hidden Process, Hidecon, and Hideexec.
Hide the Batch Console With a Visual Basic Script
Hiding the batch script console window using Visual Basic is quite similar to using an external command and works in basically the same way. Launch the VB script and supply the batch file as an argument, then the code runs the script while not showing any output. It can be done with a single line of code.
CreateObject(“Wscript.Shell”).Run “””” & WScript.Arguments(0) & “”””, 0, False
Create an empty text file, copy and paste the above line then save it as a .vbs file. Alternatively, download launchquiet.vbs which is a ready made script. To add it to a shortcut or a startup location etc, use the commands in the following way. Don’t forget to use quotes if your paths or filenames contain spaces.
Wscript [path to .vbs file] [path to .bat file]
If you would like to supply an argument for the batch file, the piece of VB script has to be altered slightly by changing the two sets of four double quotes to two sets of two.
CreateObject(“Wscript.Shell”).Run “” & WScript.Arguments(0) & “”, 0, False
Then supply the arguments along with the batch script path inside quotes:
Wscript [path to .vbs file] “[path to .bat file] [argument]”
Again, for convenience, you can download a ready made launchquiet_args.vbs script file.
On the next page, we’ll look at how to convert a batch script into an executable file, how to create a batch executable without any additional software and how to run a script from a scheduled task.