开发者

Execute as console application when parameter is set

a few days ago, I developed a WinForms application in C# using VC#2010 Express. After creating and saving the project, I made it a console application in the project settings, so additional to the start form, a windows command line pops up. I used the console to output debug information (simply with the Console.Write() function).

So now, my app is ready for a release. I do not want the user to see the console, for sure, but I'd like to integrate a way to show the console to interested persons. So, the best way is an argument, I think (like -console), but I dont know how to start the program as a console application only when an argument is set. I know how to handle the args[] array, for sure, but I have no idea how to show the console when there is an arg. I already tried it by simply starting the program via command line(CMD -> prog.exe), but it did开发者_高级运维 not work. The program starts, but the console directly shows the current path after starting the program, as usual.

Is there any possibility for my intention?


AFAIK, there is no way to have a single binary support both console and non-console behaviour, with the choice being made on start-up. All the work-arounds I've seen use two binaries.

There's a discussion here on how Python deals with the problem (boldface mine):

The standard Python.exe that comes with Python is known as a console application (this means it has been built to interact with a Windows console, otherwise known as a DOS box or command prompt). Although you can execute your Tkinter programs using Python.exe, your program will always be associated with a Windows console. It works just fine, but has the following side effects:

  • If you execute Python.exe from Windows Explorer, a new empty console window is created; then the Tkinter windows are created.
  • If you execute a Tkinter application under Python.exe from a command prompt, the command prompt doesn't return until the Tkinter application has finished. This will be a surprise for many users, who expect that executing a GUI program returns the command prompt immediately.

To get around this problem, Python comes with a special GUI version called Pythonw.exe. This is almost identical to the standard Python.exe, except it's not a console program, so doesn't suffer the problems described previously.


You could get the command line arguments for the Winform in the forms load event and then if the argument is for the console, open the console.

private void Form1_Load(object sender, EventArgs e)
{
    string[] args = Environment.GetCommandLineArgs();
    foreach(string arg in args)
    {
       if(arg == "consoleargument")
       {
           // Run console
       }
    }
}


You can link to kernel32.dll and use the function AttachConsole. Here's an example: http://www.csharp411.com/console-output-from-winforms-application/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜