Close C# Console After Code Execution in MacOS - c#

I'm writing a small program to take care of some automated plotting. I'm using a console application which simply runs through the code a finished by exporting a pdf file of the plot.
Since I'm in the testing phase, I need to run the program every time I want to see the effect of a change/addition. This means I get a lot of open console windows very fast, which I would like to avoid if possible.
Is it possible the close the console window programmatically?
I've tried Environment.Exit(), but it does not appear to do anything.
Minimum example
static void Main(string[] args)
{
//Put any or no code here
}
I'd expect the console window to close upon completion of the Program.Main() method. Instead, the console asks for 'any key' input and does not close after a key is pressed.
Console output:
Press any key to continue...
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process Complete] (<- translated from danish)

This is a setting in the Terminal Preferences in macOS itself.
Open Terminal -> Open Terminal context menu in the top left -> Select Preferences... -> Select your Terminal Profile -> Go to Shell tab -> Select "Close if the shell exited cleanly" in the dropdown menu.

Related

"Press any key to continue..." message shown in "Start Without Debugging" mode

I created a blank C# console application in Visual Studio as shown below:
using System;
namespace ConsoleApplication1
{
class Solution
{
static void Main(string[] args)
{
Console.ReadLine();
}
}
}
When I use the default Start Debugging option by pressing F5 then the program runs normally as expected. I press Enter and program ends.
But when I use Start Without Debugging option by pressing Ctrl+F5 it shows me an extra message on console after I press Enter:
Press any key to continue...
Then I've to press an additional key on the keyboard to terminate the program. From where is this magical message coming and why it is shown only in Start Without Debugging option?
Note:Post-build event command line of the project is completely empty.
That is simply how visual studio runs console programs not in debug mode. As far as I am aware it can not be controlled. Since it shows that it is actually a cmd.exe instance and not just a console window I assume VS uses the /K flag on the command line (I had thought it used a batch file but now see there is no need for that).
It is done for the typical case where a console program runs and simply exits, without that message such a program would not give any chance to see the output.
I was able to validate the information shared by #SoronelHaetir in his answer. I'm detailing out the same here with the help of some screenshots which will complement the information in his post and help you understand the same better:
When I run the application using the default Start Debugging option by pressing F5, we can see the executable of the application getting launched in task manager:
When I right click on the task and choose Go To Process option from context menu, I'm taken to a process on the process tab having image name ConsoleApp1.exe *32 as shown below. This makes perfect sense.
Now when I run the application using Start Without Debugging option by pressing Ctrl + F5, we do not see the executable of the application getting launched in task manager. In fact we see cmd.exe being launched as shown below:
Now, when I right click on the cmd.exe task and choose Go To Process option from context menu, I'm taken to a process on the process tab having an image name cmd.exe *32 as shown below. But there is more to it. You also see ConsoleApp1.exe *32 running in the process tab which was not visible in Applications tab.
So this is how all the dots get connected that in Start Without Debugging mode Visual Studio in fact launches a cmd.exe instance which in turn launches our application ConsoleApp1.exe.
The moment I press enter, ConsoleApp1.exe process gets terminated but cmd.exe process continue to live on until I press another key as shown below:

How to debug a C# .NET application in Visual Studio 2010 that is started from another process

I have a .NET GUI application written in C# and a PDF printer. The PDF printer has a field where you can set a command to start an external application.
In this case, I can print a document with this printer and the printer starts my EXE file with the filepath to the generated PDF file as argument. How can I debug my application when it is started from the printer?
In Visual Studio 2010, I can set debug information for command line arguments, and this works fine. But if the application is started from the printer the application doesn't work fine. Therefore I want to debug my application when it is started from printer. How can I do this? Is there a parameter to start an EXE file in debug mode or something like this?
Try to attach to the process:
http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx
To attach to a running process
1.On the Debug menu, select Attach to Process. If no project is open, select
Attach to Process on the Tools menu.
2.In the Attach to Process dialog box, find the program that you want to
attach to from the Available Processes
list.
a.If the program that you want to
debug is running on another computer,
you must first select the remote
computer. For more information, see
How to: Select a Remote Machine.
b.If the process is running under a
different user account, select the
Show processes from all users check
box.
c.If you are connected through Remote
Desktop Connection, select the Show
processes in all sessions check box.
3.In the Attach to box, make sure that the type of code you will debug is
listed. The default Automatic setting
tries to determine what type of code
you want to debug. If the automatic
setting is not appropriate:
a.Click Select.
b.In the Select Code Type dialog box,
click Debug these code types and
select the types to debug.
c.Click OK.
4.Click Attach.
The Available Processes list is
displayed automatically when you open
the Processes dialog box. Processes
can start and stop in the background
while the dialog box is open. However,
the contents are not always current.
You can refresh the list at any time
to see the current list of processes
by clicking Refresh.
You can be attached to multiple
programs when you are debugging, but
only one program is active in the
debugger at any time. You can set the
active program in the Debug Location
toolbar or the Processes window. For
more information, see How to: Set the
Current Program.
All Debug menu execution commands
affect the active program. You can
break any debugged program from the
Processes dialog box or break all
attached programs from the Debug menu.
For more information, see How to:
Break Execution.
You can attach to a process when it starts using a small registry tweak.
Go to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
Create a new key with the name of the executable as it will appear in Task Manager, for example, myapp.exe. Under this, create a new string value called debugger and set it to vsjitdebugger.exe.
Now, when the EXE file is triggered, a window will appear asking which debugger to attach to.
Consider adding a call into your code that explicitly requests that the debugger be attached at the current location. This has been around since Win32 days, and surfaces in .NET as System.Diagnostics.Debugger.Break (and System.Diagnostics.Debugger.Launch).
You can also add logic to decide when to trigger this if you don't want to do it the first time through:
#if DEBUG
if (++staticCounter > 3) System.Diagnostics.Debugger.Break();
#endif
And, of course, you'll want to disable it for production.

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

I just open a console application and I type
Console.WriteLine("Test");
But the output window doesn't show this. I go to the output window with Ctrl + W, O.
But nothing shows up when I run my program. Am I nuts or is this not supported in Visual Studio 2010 Express?
Console.WriteLine writes your output to the console window opened by your application (think black window with white text that appears when you open the Command Prompt.) Try System.Diagnostics.Debug.WriteLine instead.
No satisfactory answers were provided.
System.Diagnostics.Debug.WriteLine() will write messages to the Output:debug window, but so much crap is constantly dumped into that window by every process under the sun, it is like finding a needle in a haystack to find your messages.
Console.WriteLine() does not write to any window in Visual Studio. I guess it will only write to the application console if your application creates a console in the first place, i.e. if it is a console application.
Go to properties in you own project in the Solution Explorer window and choose application type and look for Output Type.
Change its value to Console Application.
This will make console screen besides your form. If you close the console screen, your form will be closed too.
Perhaps the console is clearing. Try:
Console.WriteLine("Test");
Console.ReadLine();
And it will hopefully stay there until you press enter.
Or you can debug by CTRL+F5 this will open ConsoleWindow waits after last line executed untill you press key.
It's more than likely because you've used Console in the namespace. For example like this:
namespace XYZApplication.Console
{
class Program
{
static void Main(string[] args)
{
//Some code;
}
}
}
Try removing it from the namespace or use the full namespace instead i.e.
System.Console.Writeline("abc");
The reason is a problem this is an issue is because you might have another clashing namespace. Example:
using System;
using AnotherNamespaceThatContainsAConsoleClass;
The output window isn't the console. Try the methods in System.Diagnostics.Debug
In a Windows Forms application, both methods,
System.Diagnostics.Debug.WriteLine("my string")
and
System.Console.WriteLine("my string")
write to the output window.
In an ASP.NET Core application, only System.Diagnostics.Debug.WriteLine("my string") writes to the output window.
Try Ctrl + F5. It will hold your screen until you press any key.
I run into a similar problem while running a unit test. Console.WriteLine() did not write anything into the Visual Studio Output Window.
Using System.Diagnostics.Debug.WriteLine() solved the problem.
None of the answers here worked for me!! Most of these people here are stuck in Windows Desktop Application Consoleland. If you are a web developer using ASP.NET in Visual Studio and do not see any console or debug text, here is how to fix that:
Paste the following two tests into your code so it runs both lines. These are tests for the output window:
System.Console.WriteLine($"hello console!");
System.Diagnostics.Debug.WriteLine($"hello debugger!");
In Visual Studio choose VIEW > OUTPUT. You will see the results above in this output window after changing two settings below.
When NOT DEBUGGING, in the OUTPUT window at the top under "Show Output From" choose: "YourProjectName - ASP.NET CORE Web Server". Run your code. You should see the "Console" text above.
When DEBUGGING, in the OUTPUT window at the top under "Show Output From" choose: "Debugger". Run your code in debug mode. You should see the "Debug" text above.
Right click on the project in Solution Explorer and click "Clean".
Now run - press F5.
Make sure the code is as below:
Console.WriteLine("TEST");
Console.ReadLine();
If you use Ctrl-F5 (start without debugging) it will leave the console window open with a message "Press any key to continue". That's the easiest way to keep the console window from closing so you can see the console output.
Go to the Debug menu and select Options and uncheck "Redirect all Output Window text to Immediate Window"
Console.Writeline() shows up in the debug output (Debug => Windows => Output).
If you are developing a command line application, you can also use Console.ReadLine() at the end of your code to wait for the 'Enter' keypress before closing the console window so that you can read your output.
using System.Diagnostics;
Trace.WriteLine("This line will show on Output window");
Trace.Flush();
This works on Microsoft Team Explorer for Visual Studio 2013
Refer to microsoft.com
The Output window of Visual Studio 2017 have a menu called Show output from, in my case ASP.NET Core Web Server was the option to select in order to see the printed out, I came across this issue since I had it set to Build so I wasn't seeing the printed out lines at runtime.
There are 2 possible problems are:
Firstly, you have not used the using System which should be before writing code that uses "System class", as Console.WriteLine()
Secondly, you have not coded what happens after the Console displays "Test"
The possible solution will be:
using System;
namespace Test
{
public static Main()
{
//Print to the console
Console.WriteLine("Test");
//Allow user to read output
Console.ReadKey();
}
}
It is also strategic to code Console.Write("Press any key to exit..."); on the line that precedes the Console.ReadKey(); to make the user aware that the program is ending, he/she must press any key to exit.
Change the execution mode to "Self Hosted". In this case, the execution console will appear and all the messages will be displayed.
A workaround I found:
Press Ctrl + Alt + I or navigate to the Debug tab → Windows → Immediate.
In your code write:
Trace.WriteLine("This is one of the workarounds");

Automatically close windows explorer

i am trying to write a program that close explorer then runs another program.
i am getting a problem when trying to close explorer using the following code:
foreach (Process p in Process.GetProcesses())
if (p.MainModule.ModuleName.Contains("explorer"))
p.Kill();
can somebody please let me know why it is doing this and provide a solution
CHEERS
p.s. this is not a malicous program, it is going to run a game that doesn't work properly when explorer is in the background
The problem is that you can have multiple versions of Explorer running at any one point in time... and you usually need at least one of them. The shell that hosts the Start Menu is actually an instance of Explorer. So if you close all instances of Explorer, you'll also be shutting down the main shell, which is not what you want to do.
However, the fastest way to do get all instances of Explorer and kill them is:
foreach (Process p in Process.GetProcessesByName("explorer"))
{
p.Kill();
}
There is a simple undocumented way to exit explorer cleanly, see also question Gracefully Exit Explorer (Programmatically). It is intended for developers working on shell extensions.
The procedure is different for Windows XP and Windows 7:
Windows XP:
Open the shutdown dialog (Start > Shutdown), then cancel the dialog pressing CTRL-SHIFT-ALT-ESC (or hold down CTRL-SHIFT-ALT and press the Button with the mouse).
Windows 7:
Open the Start menu and then hold CTRL-SHIFT while right-klicking into the empty area of the start menu, see screenshot. A context menu appears, where the second entry is 'Exit Explorer' (without CTRL-SHIFT the context menu has only one entry)
p.s. this is not a malicous program, it is going to run a game that doesn't work properly when explorer is in the background
Explorer is a critical Windows component. You should debug why you have problems when Explorer is running, and fix those.
Killing Explorer will cause severe problems for your users.

What exactly is a "Console"?

I am trying to writing a console application. It has its original console, let's name it console A. And I want this application to do the following things via C#:
Open another console B in another thread, then get input from A and output it to B;
type a command in A, such as dir, and show the output in B;
while doing the above things (still not done yet. X_X ), I find myself lack a through understanding of what a console window is, and how it is assigned to a console application, especially the very first console when my console application starts to run. Could some one shed some light on me?
Is console window physically a memory area in the video memory? Or something else?
Could different threads within the same process have different console of its own for its own I/O?
Many thanks.
Now I am using one console application to start another console application in a new process. Thus I can have 2 consoles output at the same time.
My understanding now is that, for Windows OS, a console is a special window, and it's a system resource that OS assigned to the application without-a-UI as a necessary user interface. Windows OS handles the wiring between the system-prepared console window with our UI-less application.
In Windows terms, a Console is a textual GUI window that you see when you run "cmd.exe". It allows you to write text to, and read text from, a window without the window having any other UI chrome such as toolbars, menus, tabs, etc,..
To get started you'll want to load Visual Studio, create a new project and choose "Console Application". Change the boilerplate code that Visual Studio produces to:
using System;
using System.Text;
namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hello, world!");
Console.ReadKey();
}
}
}
When you run your application, a console window will open with the text "Hello, world!" and it'll stay open until you press a key. That is a console application.
Is console window physically a memory area in the video memory? Or something else?
It's not physically a memory area in video memory, it's "something else". The Wikipedia Win32 console page gives a fairly robust descrption of the ins and outs.
A console application has only one window. It does not have window management functions in order to spawn child "consoles".
You can start additional console applications, but these are separate entities.
No. It's a windows GUI subsystem. In WinAPI there are functions to work with console: http://msdn.microsoft.com/en-us/library/ms682073%28VS.85%29.aspx
A (OS) console is a process (containg one or more threads of executions, all of them sharing the same memory space), and this process has:
standard input (a stream of input bytes), what you key in
standard output (a stream of output bytes), what the program prints
standard error (a stream of output bytes), what the program prints when it's complaining about something
So if you want to create another console (from .Net) and link the input/outputs I understand you have to create a process (executing "cmd.exe" by example).
I don't know the API of .Net for process manipulation but if it's like Java you can hook up stdin, out and err so you can play with your created process from the original one.
A windows application can have one console, or no console, it can't have more than one. See the documentation for AllocConsole.
The console is basically an emulation of the 'pre-Windows' days when there would literally be a 'control console' i.e. a keyboard and screen attached to a mainframe computer.
To do what you want you could spawn another process with its own console and communicate between the two, or make a GUI application which looks like a console window.

Categories