Seeing the console's output in Visual Studio 2010? - c#

I am writing a simple C# program with some outputs (Console.WriteLine("...");). The problem is, each time I run it, I cannot see the program's output in the output window.
The "program output" tag is already checked, and I already redirected all outputs to the intermediate window but to no avail.
How do I enable seeing the program's output?
I don't think the problem lies with my code. I tried running a simple program that just outputs a string and readline "ala hello world" and I am still unable to see any output. The problem is either with me looking for the output in the wrong location or Visual Studio acting out.
The debug.write method also doesn't work.
Using debug.Write, it all works, though it didn't before. Either something bugged out with me before I restarted or I just need to take a break, either way it's all good now. Thanks all for the helpful comments =)

You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.

Here are a couple of things to check:
For console.Write/WriteLine, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine).
You could use System.Diagnostics.Debug.WriteLine to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline)

Add a Console.Read(); at the end of your program. It'll keep the application from closing, and you can see its output that way.
This is a console application I just dug up that stops after processing but before exiting:
class Program
{
static void Main(string[] args)
{
DummyObjectList dol = new DummyObjectList(2);
dol.Add(new DummyObject("test1", (Decimal)25.36));
dol.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
dolxs.Serialize(Console.Out, dol);
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
List<DummyObject> dolist = new List<DummyObject>(2);
dolist.Add(new DummyObject("test1", (Decimal)25.36));
dolist.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
dolistxs.Serialize(Console.Out, dolist);
Console.Read(); // <--- Right here
}
}
Alternatively, you can simply add a breakpoint on the last line.

Press Ctrl + F5 to run the program instead of F5.

System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.
P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.

To keep open your windows console and to not use other output methods rather than the standard output stream cout go to Name-of-your-project -> Properties -> Linker -> System.
Once there, select the SubSytem Tab and mark Console (/SUBSYSTEM:CONSOLE). Once you have done this, whenever you want to compile use Ctrl + F5 (Start without debugging) and your console will keep opened. :)

I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:
Click View → Output (or just hold Ctrl and hit W > O)
Console output then appears where your Error List, Locals, and Watch windows are.
Note: I'm using Visual Studio 2015.

Visual Studio is by itself covering the console window, try minimizing Visual Studio window they are drawn over each other.

In Program.cs, between:
static int Main(string[] agrs)
{
and the rest of your code, add:
#if DEBUG
int rtn = Main2(args);
Console.WriteLine("return " + rtn);
Console.WriteLine("ENTER to continue.");
Console.Read();
return rtn;
}
static int Main2(string[] args)
{
#endif

You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.
This way you can determine when your functionality gets executed and also when the program exists.
startProgram()
{
Console.WriteLine("-------Program starts--------");
Console.Read();
}
endProgram()
{
Console.WriteLine("-------Program Ends--------");
Console.Read();
}

Related

When using input = Console.ReadLine(); it doesnt go to the next line of code, it simply loops when I put anything

Quick note: I come from python and other easier to use programming languages.
I dont know why it doesnt go and continue to the next line, this is the steps I took, I firstly run the script in visual studio and it runs and then I can input text into the debug console, I type something and it repeats the line of input so I input again and it doesnt go onto the next line it just loops at input = Console.ReadLine();, I even tried copying code from the internet that simply asks for input and prints it and it does the same thing, I think its something to do with visual studio maybe, This is a first so I apologize if I made a mistake, thank you for your help.
here is the code:
using System;
using System.IO;
namespace Printing
{
class Program
{
static void Main(string[] args)
{
string input;
Console.WriteLine("Please enter a number for the times table");
input = Console.ReadLine();
Console.WriteLine("number is: " + input);
for (int i = 0; i < 10; i++)
{
if (i != 0)
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}
}
OMG This was very annoying and finally found a way of fixing this, for what ever reason the internal console does not work at all at least on my linux system, I found a post 4 years old mention changing the console to integratedTerminal and that fixed it, it works now, to change the console go to your launch.json file and change internalconsole too integratedTerminal.
very frustrating but now its done.
Something may be wrong with your Visual Studio. I've run your code in my computer and it works perfectly fine, nothing loops. Is VS updated to the latest version? Check Visual Studio Installer. And what console are you using? Is it the default Windows CMD? My advice would be to reinstall VS if it still doesn't work.

Why is my clipboard-manipulating application behaving differently when run outside of Visual Studio?

I have a console app with an "output type" of "Windows Application" (to achieve a headless behavior, i.e. no UI, no console window). The purpose is to "clean" text in the Windows clipboard, i.e. trim all leading and trailing whitespace and remove formatting.
It works great when debugging, but when I run it from explorer, it just clears the clipboard contents.
Here's my code:
[STAThread]
internal static void Main(string[] args)
{
var currentClipboardText = System.Windows.Clipboard.GetText();
// only if the clipboard has text; leave any other content intact.
if(!string.IsNullOrEmpty(currentClipboardText))
{
currentClipboardText = currentClipboardText.Trim();
var pattern = #"[\t\r\n\v\f\u2028\u2029]"; // match vert. whitesp & tabs
currentClipboardText = Regex.Replace(currentClipboardText, pattern, " ");
System.Windows.Clipboard.SetDataObject(currentClipboardText);
}
}
Sample input with formatting in MS Word, copied to clipboard:
After I run the program in the dubugger (either in "debug" mode or "release" mode, makes no difference), here is the result pasted back into Word from the clipboard:
If I do the same excercise but run the program by double-clicking on it in Windows explorer (i.e. in the \bin\Debug directory), there is no text left on the clipboard to paste into Word:
What is the difference here? Why isn't it working outside of Visual Studio?
By default, data placed on the system Clipboard with SetDataObject is automatically cleared from the Clipboard when the application exits.
MSDN
Use System.Windows.Clipboard.SetDataObject(currentClipboardText, true); instead to keep the data in the clipboard after the application exits.
I have tested your code, and it does not work when debugging. I changed the line:
System.Windows.Clipboard.SetDataObject(currentClipboardText);
With:
System.Windows.Clipboard.SetText(currentClipboardText);
And it worked when debugging, and when not debugging. I think what is happening is that Word is no longer recognizing the DataObject as being paste-able text.
I hope this solves your problem.

Can't send keys (string) to notepad

I thought that code is pretty good, bu it isn't. I'm trying to add something text to my notepad, which look like:
string text = "TESTTESTTESTTEST";
[DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr hWnd);
public void EditTxtFile(string text)
{
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr handle = p.MainWindowHandle;
SetForegroundWindow(handle);
SendKeys.SendWait(text);
p.Kill(); //also process doesn't shoutdown
}
}
When i try to debug this function (actually SendKeys), that message is showing up:
Changes are not allowed while code is runnig.
If it's important i try to edit this from web page/application.
The problem is, that Visual Studio catches Focus when it hits the break point, and then SendKeys is send to Visual Studio instead of notepad, and this produces the error.
What you can do ist the following:
Right Click on the Breakpoint and select "When Hit..."
There you can output whatever you want without Notepad losing Focus
Problem was in function which was responsible for opening that notepad (not enough time to start and open him). I've just add wait function for 4s.
To mine, it's about I use a reference value text from the source WinForms's control, call SendKeys' function while the source form is not yet close or hide before (still the active form). This can produce a similar result: SendKeys.Send() or SendKeys.SendWait() does not send a desired text to the target application.
The steps to workaround this:
1. transfer the text value from the active form to a new temporary variation or a Clipboard,
2. close or hide the active form,
3. activate the target application's form,
4. wait a bit to ensure the target application's form to become active 5. and give the temporary text variation or Clipboard to SendKeys. Works.
PS: Please make sure your application has runtime permission equals or more than the target application.

Console.WriteLine does not show up in Output window

I have put some Console.WriteLine calls in to test, but they aren't appearing in the output box?
public static ArrayList myDeliveries = new ArrayList();
public mainForm(){
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e){
if (!File.Exists("../../MealDeliveries.txt")){
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")){
//first line is delivery name
string strDeliveryName = sr.ReadLine();
Console.WriteLine("Test content");
while (strDeliveryName != null){
//other lines
Delivery d = new Delivery(
strDeliveryName,
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine()
);
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
private void displayDeliveries(){
lstDeliveryDetails.Items.Clear();
Console.WriteLine("Test content");
Console.WriteLine(mainForm.myDeliveries.Count);
foreach (Delivery d in mainForm.myDeliveries){
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
Can anyone help??
Console outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine to send output to the output window in your IDE.
Edit: In regards to the problem, have you verified your mainForm_Load is actually being called? You could place a breakpoint at the beginning of mainForm_Load to see. If it is not being called, I suspect that mainForm_Load is not hooked up to the Load event.
Also, it is more efficient and generally better to override On{EventName} instead of subscribing to {EventName} from within derived classes (in your case overriding OnLoad instead of Load).
If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.
If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.
If you absolutely must use the console, then you can attach a console in the program's Main method.
If you want Console.WriteLine("example text") output to show up in the Debug Output window, temporarily change the Output type of your Application from Console Application to Windows Application.
From menus choose Project + Properties, and navigate to Output type: drop down, change to Windows Application then run your application
Of course you should change it back for building a console application intended to run outside of the IDE.
(tested with Visual Studio 2008 and 2010, expect it should work in latter versions too)
Using Console.WriteLine( "Test" ); is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.
However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" ); was working. I restarted Visual Studio and Console.WriteLine() started working again. Seems to be a Visual Studio bug.
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. However, both the Trace and Debug answers posted above are better options.
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
Try to uncheck the CheckBox “Redirect all Output Window text to the Immediate Window” in
Tools => Options => Debugging => General
I had it checked and everything was written in the Immediate Window and not in the Output Window
When issue happening on Mac VS 2017 (Which I faced).
Go to Project >> "Your Project name" options.
An option window will pop up
Go to RUN >> Default menu option
Tick the "Run on external console" option TRUE and say OK
Run your application code now.
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab

Reading console input in MonoDevelop

I am trying to a simple C# program that takes input and passes it as output. For instance, the output should be:
What is your name?
{user input}
Your name is {user input}
The program is:
public static void Main(string[] args)
{
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine("Your name is: " + name);
Console.ReadKey();
}
This is enclosed in a class called 'MainClass'
Its output is:
What is your name?
Your name is:
Why is this not working and how can I make it work?
P.S. I am using MonoDevelop and I added Console.ReadKey(); after the last WriteLine. No change.
You are trying to type in the Application Output window in MonoDevelop and it is read-only.
You can configure MonoDevelop to automatically run the program at the command prompt by right clicking on the "options" menu item of your project and checking Run on external console under the Run > General tree.
alt text http://psf.biz/public/monodevelop_run_on_external_console.jpg
I guess the guy that gave me the -1 was blinded by that huge "Works on My Machine" emblem, nevertheless this is the correct and only answer.
(source: typepad.com)
Is your problem that the program quits immediately after reading the console input? If so, then add a Console.ReadKey(); after the last WriteLine so the program will wait for a keypress. Otherwise, I don't know what the problem is; I copy+pasted the code and it worked.

Categories