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
Related
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.
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.
I have a simple application that opens a TCP connection and communicates via Telnet to another system. The application is to read a file that contains parameters and a simple scripting language to issue commands based on prompts from the connection.
Written in VS2013 using .NET 4
My application works as designed with one little exception.
I am publishing to a location using VS2013 which works well enough but the idea is to read a command line passed to my application that contains the path/file for the script to execute and that doesn't work as expected.
Finding out the hard way, the standard args[] parameters are not passed when it's published this way.
I have searched out multiple solutions that don't work both on here and other sites.
This is the basis (excerpt from page) of my current implementation to read the command line (found here: http://developingfor.net/2010/06/23/processing-command-line-arguments-in-an-offline-clickonce-application/). This seems to be similar to all solutions I've found, each with some variation that doesn't work.
string[] args = null;
if (ApplicationDeployment.IsNetworkDeployed)
{
var inputArgs = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
if (inputArgs != null && inputArgs.Length > 0)
{
args = inputArgs[0].Split(new char[] { ',' });
}
}
else
{
args = e.Args;
}
This SHOULD return args[] with parameters passed. I believe it would also include the actual command with path to the application. The Split function is because the author wishes to pass arguments separated by commas and not spaces.
My incarnation of this is a bit longer to include some checks to see if we actually get arguments from being compiled as an exe instead. If I compile to EXE and supply a command line, all is fine. Here is my code, not very concise as I've made lots of changes to debug and make this work.
I haven't figured out how to debug in the ide as network deployed with a command line so my debug code is via messagebox.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length == 0) //If we don't have args, assume onclick launch
{
if (ApplicationDeployment.IsNetworkDeployed) //are we oneclick launched?
{
var cmdline = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData; //this should hold the command line and arguments????
if (cmdline != null && cmdline.Length > 0) //we have something and it contains at least 1 value
{
//This is all debug code to see what we get since we can't trace in this mode
MessageBox.Show(cmdline.Length.ToString()); //how many objects do we have?
foreach (String s in cmdline)
{
MessageBox.Show(s); //show us the value of each object
}
Application.Run(new frmMain(args)); //launch the form with our arguments
}
else
{
//quit application
MessageBox.Show("No command line.1"); //debug so we know where we failed
Application.Exit();
}
}
else
{
//quit application
MessageBox.Show("No command line.2"); //debug so we know where we failed
Application.Exit();
}
}
else
{
Application.Run(new frmMain(args)); //launch form with args passed with exe command line
}
}
Running the code above like this:
sTelent.application 1234
I have also explored the URL passing method which seems to only apply if launched from a web server, which this application is not.
At first I got NULL for my object:
AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData
After more research I discovered that in my project properties under the Publish section there is an option button and under Manifests I can choose "Allow URL Parameters to be passed to application"
I checked this box and while I get different behavior, I don't get the desired behavior.
With that option checked I now get 2 messages boxes: The first showing the number of objects in cmdline and that number is 1 and the second showing the value of that one object which contains only the path/command to my application. No other objects and definitely not my arguments.
Am I totally off base? How do I get my command line arguments from an offline clickonce published application?
It seems that you must put the argument on the .appref-ms and not on not the .application or .exe for this to work correctly for clickonce based applications.
I created a short cut on my desktop by copying the installed application link found under All Programs. That should create an icon on your desktop with the same name as your application.
Then, open a command prompt, type in “%userprofile%\Desktop\My App Name.appref-ms” word for word (of course replace "my app name" with your application name). It should then pass the arguments. You can also put the command within a .bat file. I'm sure that you can also reference the link directly, it typically is located under c:\users[user profile]\appdata\roaming\Microsoft\windows\start menu\programs[app name]
Im having some trouble my program hanging when selecting a file in a file dialog. This is the code that is showing the file browser dialog:
private void isForgeIncluded_btn_Click(object sender, EventArgs e)
{
this.isForgeIncluded.Text = FolderFileDialog("file", isForgeIncluded.Text, "Forge installer file (*.jar)|*.jar");
}
public string FolderFileDialog(string type, string current, string fileTypes = "All files (*.*)|*.*|All files (*.*)|*.*", string StartFolder = "C:\\")
string ReturnString = current;
if (current != "")
{
StartFolder = Path.GetFullPath(current);
}
if (type == "file")
{
OpenFileDialog minecraftFile = new OpenFileDialog();
minecraftFile.Title = "Select file";
minecraftFile.InitialDirectory = StartFolder;
minecraftFile.RestoreDirectory = true;
minecraftFile.Filter = fileTypes;
if (minecraftFile.ShowDialog() == DialogResult.OK)
{
ReturnString = minecraftFile.FileName;
return ReturnString;
}
minecraftFile = null;
}
return ReturnString;
}
I've narrowed the problem down to between the "if" statement and the "Return string = minecraftFile.FileName;" .. When using the debugger the program takes up to a five second break between those two lines. After its break it comes back and returns the value as if nothing was wrong. But IntelliTrace sometimes comes up with a "FileNotFound Exception" even though the program never shows me any error messages, and returns the correct value to the textbox as it should.
The wierd part is that it is not always this happens. Its random and can happen even though i select the same file as last time. The files i select are local files too on the system drive.
What could be wrong? Does the code look as it should?
Two basic problems can cause trouble with OpenFileDialog. First is misbehaving shell extension installed on your machine, they'll get loaded into your process when you open the dialog. A basic check is that you don't see trouble with Notepad's File + Open command and that you see nothing special in the Visual Studio Output window while the dialog is active. Enabling unmanaged debugging gives you more info.
The second cause is having an issue with the thread state of your UI thread. If must be initialized as a single-threaded apartment to be able to show this dialog properly. Go back to your Main() method, normally in Program.cs, and ensure it has the [STAThread] attribute.
If that doesn't pan out then we need more info about the code that's misbehaving. You need to enable unmanaged debugging, Project + Properties, Debug tab. And enable the Microsoft symbol server, Tools + Options, Debugging, Symbols. And disable Just My Code debugging, Tools + Options, Debugging, General. Hit Debug + Break All right after you get it to misbehave and post the content of the Call Stack window.
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();
}