I searched the web and Stackoverflow, I didn't find anything.
I am sorry if this question already exists.
If my C# application is called through the cmd for example:
C:\System32\MyConsoleApplication -parmOne -paramTwo ...
Is there a way to write into the cmd (for example to giving progressinformation?)
Edit: Cause I use a Consoleapplication the solution ist Console.WriteLine It doesnt worked for me cause my application requires adminrights (trough a Manifestfile) and was called with normal userrights. In this case the UAC asks for rights and opens a new Cmd with the application.
better solution : http://www.nerdyhearn.com/blog/157/
here is the code of the site:
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
[STAThread]
static void Main(string[] args)
{
// Enable visual elements just like always
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Attach to the parent process via AttachConsole SDK call
AttachConsole(ATTACH_PARENT_PROCESS); // <-- important point here
Console.WriteLine("This is from the main program");
Application.Run(new Form1());
}
You can use the AttachConsole call at your will in the special conditions you need. This is much better and flexible and does not require you to change your application manifest. if its a win32 app, wll good for your app. if its launched from a cmd then the output will appear as excpected.
My opinion: this is just some useless microsoft complication of some concepts that are so pure and natural in the Unix world. If your application is launched from a visual launcher (icon, nautilus..) then the output is lost. You can launch your app from a console and its gets in the console. you can redirect the output if you need, it all imbricates logically and its powerful. With microsoft... its bloated and gets in the way of everybody.
This all depends on what the exe type is - which is a flag in the PE-header (the "exe" shell):
if it is flagged as a windows app, it doesn't get a console / output to the existing console - regardless of how it is started
if it is flagged as a console app, it does get a console / output to the existing console - regardless of how it is started
It cannot be both. It you want it to work like a windows exe normally, then you will have to compile it as a windows exe, which means no: it won't write to the console normally. Trying to acquire access to the console from a windows exe is tricky, and would require P/Invoke to the OS.
If it is flagged as a console exe, then just Console.WriteLine will work fine.
Related
I realize this sort of question has been asked before, but I have a very specific (and a rather complicated) case that is subtly different, so the usual solutions either do not work or do not apply.
Basically, I have a console app which is launched by a VSIX debugger launcher. The purpose of this app is to load a hosted DLL, establish the appropriate environment, and allow debugging of the DLL's source code from Visual Studio the same way a normal C# project would be debugged. The difference is that this project is not an executable, but a library, and so it needs a host (i.e. the console app in question). It's all very similar to how ASP.NET projects work with IIS/IIS Express - it's just that I wrote a custom host and I manage its launching from my custom VSIX.
The custom host app is a .NET Core Console app and the debugger launches it without any windows. This is deliberate, since it needs no interactive input and all output is redirected to the Visual Studio's debugger session (i.e. the Events tab).
The app is also generic, so it can't know the name of the debugged project until it's actually started. On top of that, I can have multiple instances of Visual Studio debugging multiple different projects at the same time!
I would really like to ease differentiation of these processes in Task Manager, so that they each showed as the name of the specific DLL project that is being hosted in each respective instance. My attempts so far have been:
// 1. This crashes with InvalidOperationException because there is no window.
Console.Title = loadedDllProjectName;
// 2. This doesn't crash, but has no effect, either.
[DllImport("user32.dll")]
static extern int SetWindowText(IntPtr hWnd, string text);
...
SetWindowText(Process.GetCurrentProcess().MainWindowHandle, loadedDllProjectName);
FWIW, the Task Manager shows the process under its default image name and lists it among background processes. The latter is fine and expected. But I would like to change the former. How?
UPDATE
According to this, my pursuit might sadly be hollow. Still hoping for an encouraging hint, though!
I'm not sure how to phrase this question so please bear with me.
I am creating a sandbox to run .exes with different privileges. Basically I'm building on the example in this article: https://msdn.microsoft.com/en-us/library/bb763046(v=vs.110).aspx
Prior to the re-design I'm about to mention, my project had a console application output type (Project->Properties->Application->Output type) despite the fact it was mainly a WPF project. This resulted in both a console window and my GUI being displayed on commencement of the program.
When running a console application IN the sandbox, the output would be written to the already open console window and not create another tied to the .exe under test. I'm trying to avoid this and would prefer my output type to remain as a windows application to prevent a needless console window being open.
As far as I can tell, the issue stems from this line of code:
target.EntryPoint.Invoke(null, parameters);
This runs the Main(string[] args) method in my .exe under test, however it doesn't spawn its own console window and errors follow swiftly. Is there some way to create a console window and attach the spawned process to it?
Thanks, edits and questions welcome
P.S. With the output type being set to console application, other output types (e.g. forms and wpf projects) load their respective GUIs perfectly fine.
The answer to my problem involves using pInvoke in order to use some of the kernal32 api. Adding these DLLImports:
[DllImport("kernel32.dll")]
static extern int AllocConsole();
[DllImport("kernel32.dll")]
static extern int FreeConsole();
These allow me to allocate a console to a process I'm about to launch and I can leave my project as a windows application. All that needs to happen is to enclose my invoke in between Alloc and Free.
As such:
AllocConsole();
var trythis = target.EntryPoint.Invoke(null, parameters);
FreeConsole();
I have a .Net windows C# application, fairly complete and working, that I have been asked to support calling it from another program like LabView. I have added the ability to parse command line arguments at startup so I can detect that it is supposed to behave like a console application and be provided with enough information to function.
What I would like to do is have the program print out to the console its results and have the calling program pipe it or just pull the data and use it.
The printing to the console works fine but when I start the program up, it tells the command prompt window that it is done (a new prompt immediately shows up and the command prompt is waiting for input). In the process it also closes the redirection that was part of the startup line. Is there anyway to keep it from telling the calling program that it has completed before it has actually finished?
The simple solution is to pass a file to save the data to but I would prefer not to have to do that. I could also do a separate version that is a console app, but that means supporting two separate programs.
Thanks
Instead of invoking the program directly, you can use cmd /c myapp.exe.
I am not quite sure about the difference among the console (in "windows console application"), cmd.exe, a shell.
I know cmd.exe is a stand-alone process when running, is cmd.exe == shell ? So shell is just a process?
is console == cmd.exe?
MSDN says ProcessStartInfo.UseShellExecute==True means use the shell when starting the process, does it mean that the process is started just the same as i run a cmd.exe and run the program from that command prompt? What's the point of doing this? Does the process started this way has its own console?
Thanks in advance.
- MSDN says ProcessStartInfo.UseShellExecute==True means use the shell when starting the process, does it mean that the process is started just the same as i run a cmd.exe and run the program from that command prompt? What's the point of doing this? Does the process started this way has its own console?
Actually it works like this:
if UseShellExecute is false, the application will be started using the CreateProcess API; this API lets you specify a lot of startup options, among which there is the possibility to redirect stdin/stdout/stderr, but will only start executables. If you try to launch a file (e.g. a word document) with CreateProcess, it will fail, because word documents aren't executable files.
if UseShellExecute is true, the process will be started using the ShellExecuteEx API; this function is the same function that Windows Explorer ("the shell", at least in Microsoft terminology) uses when you double click on a file in a folder; its main advantage is that it "knows" how to start documents (opening them with the associated programs), it's aware of shell folders, ... because it uses a lot of the shell facilities. However it has some major drawbacks: it's quite heavyweight compared to the bare CreateProcess (because it has to perform a lot of extra work), it fails to open even executables if something is wrong with file associations/shell extensions/... and it can't redirect stdin/stdout/stderr. Not that theoretically it would be impossible: after all ShellExecuteEx internally calls CreateProcess; the problem is that it doesn't expose this feature.
So, the two methods of creating a process are really quite different; the Process class does a great job at flattening them, but a feature that absolutely cannot be reproduced with the ShellExecuteEx function is the IO streams redirection, since it's not made available by the ShellExecuteEx function and it can be enabled only at process start via CreateProcess.
The use of the console by the started program is another question. The console is allocated/reused inside CreateProcess (actually IIRC it has to do with the windows PE loader, that checks the required subsystem in the PE header); the rules for console creation/reusing are specified here.
If the started application is a GUI application, no consoles are created at all; on the other hand, if a console application is started it reuses its parent process' console, unless it specified in the CreateProcess call the CREATE_NEW_CONSOLE flag. The default is not to specify this flag, but I'm not sure of what does ShellExecuteEx do with console applications, and I don't have a Windows box at hand to check. I'll leave this as an exercise to the reader. :P
Additional answers
Hi, Matteo, another question. If i create a new process as a detached process which don't have a console attached. Where is the process's stdout now? Where does's the process's output go? Is the process's stdout differnt from console's ouput?
It's not clear to me what you mean. When you start a new process with CreateProcess/ShellExecuteEx the console is allocated as needed, i.e. if the exe is a console executable (as specified in the PE header), Windows provides it a console (that is a new one or the parent's one depending on the rules I specified above); if the exe is a GUI application no console is allocated for it.
IIRC, for GUI applications stdout/stdin/stderr are just bit buckets, i.e. they point to nothing useful and all IO to them is discarded; by the way, nothing stops a GUI application from allocating a console and redirecting its own std* streams to it.
Keep in mind that the console, the Windows std streams and the CRT std streams are three separate things. The console is just an interface, that for console applications is conveniently bound by default to the Windows std streams.
The Windows std streams are the ones that are redirected when you specify stdin/stdout/stderr redirection in CreateProcess; you can get handles to them with the GetStdHandle function, and redirect them with the SetStdHandle.
The CRT stdin/stdout/stderr, finally, are yet another abstraction, built by the C runtime library; they are bound by default to the Windows std streams.
All this normally work seamlessly and you don't even have to bother about the difference between the Windows std streams and the CRT streams; however, when you start to think about streams redirection this difference becomes important.
If process's stdout stream is differnt from console's output, And Shell make the binding of these 2 streams for us. Would the ouput of a process be copied from process.stdout to console.output? is that efficient?
The shell isn't involved in this process, is the kernel that does the plumbing, following the instructions used in the CreateProcess (or subsequently modified from inside the new process with other APIs). For your performance concerns, with a layered structure like this it's the only way to go; and moreover, the copying part (if it's really a copy, I suspect that the whole thing is just a matter of passing pointers around) is the fastest part of the process, the real bottleneck is the console window painting/scrolling/etc. In facts, if you want to run a console application letting it produce data at full speed, you usually redirect its standard output to a file or through a pipe.
Many many thanks. Matteo Italia. You are a good problem sovler. :D
Thank you. :)
As far as I know:
Shell: A interface for the operating system and ultimately, the kernel. this includes explorer.exe and cmd.exe
Console: You instantiate the Win32 Console. That is the window that outputs your Console.WriteLine
cmd.exe : the windows command line interpreter. it instantiates the Win32 Console
More reading:
http://en.wikipedia.org/wiki/Win32_console [The win32 console, the console that you use if you don't require a graphical user interface]
I'm trying to launch an external updater application for a platform that I've developed. The reason I'd like to launch this updater is because my configuration utility which handles updates and license configuration for the platform has shared dependencies with other assemblies in the folder where the update will be deployed. So, while I can rename the configuration utility and overwrite it when deploying the update, I can't rename or overwrite the DLLs it depends on. Hence, the external updater application.
I'm handling all of the update gathering logic in the configuration utility, then attempting to launch the updater to handle the actual file copy/overwrite operations. Obviously, because of the file in use issues, I need the configuration utility to exit right after the updater begins.
The problem I'm having is that I'm using the standard Process.Start method of launching the updater, and as soon as the configuration utility exits, the updater process gets killed too.
Is there any way that I can create a Process that outlives its parent, or launch an external application that can run beyond the program that launched it?
EDIT:
Apparently, in my updater application, I miscalculated the number of command line arguments which are passed to it. Because of this, the updater would exit immediately. I misinterpreted this to mean that the launcher application was killing the "child" process, when in fact, it wasn't.
The answers below are correct.
It seems that the problem you are seeing has a different reason because the Process class will not kill any processes started using Process.Start when your application exits.
See this simple sample program, the calculator will stay open:
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Process.Start(#"C:\windows\system32\calc.exe");
}
}
There's no reason why a process started with Process.Start should automatically die when the launcher exits. My guess is that you're doing something odd in the updater.
I've written an updater doing exactly this kind of thing before, and it's been fine.
For example:
Launcher.cs:
using System;
using System.Diagnostics;
class Launcher
{
static void Main()
{
Console.WriteLine("Launching launchee");
Process.Start("Launchee.exe");
Console.WriteLine("Launched. Exiting");
}
}
Launchee.cs:
using System;
using System.Threading;
class Launchee
{
static void Main()
{
Console.WriteLine(" I've been launched!");
Thread.Sleep(5000);
Console.WriteLine(" Exiting...");
}
}
Compile both of them, separately, and run Launcher.exe. The "launchee" process definitely lasts longer than the launcher.
Just a thought from my foggy memory, but I seem to remember having a discussion a while back that when the Process.Start method is called from Form that the spawned process has some sort of dependency (not sure what, why or how, memory is a bit foggy).
To deal with it, a flag was set that was actually called from the Main() method of the application after the main form/app exited and that if the process was launched from the Main() method, eveything worked out just fine.
Just a thought, like I said, this is purely from memory, but some of the examples posted here all being called from the Main() method of a console app seemed to jog something.
Hope all works out well for you.