C#: Is it possible to have a single application behave as Console or Windows application depending on switches?

前端 未结 7 2268
无人及你
无人及你 2020-12-09 21:25

I have a simple application that I would like to sort of automate via switches. But when I do run it via switches I don\'t really want a user interface showing. I just want

7条回答
  •  -上瘾入骨i
    2020-12-09 22:16

    You can, but with some drawbacks:

    You can prevent having this black window on start up if you compile for subsystem Windows.

    But then you have to attach the process to the calling console (cmd.exe) manually via AttachConsole(-1) http://msdn.microsoft.com/en-us/library/windows/desktop/ms681952%28v=vs.85%29.aspx

    This alone does not do the job. You also have to redirect the three std streams to the console via these calls:

    // redirect unbuffered STDOUT to the console
    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    
    fp = _fdopen( hConHandle, "w" );
    *stdout = *fp;
    setvbuf( stdout, NULL, _IONBF, 0 );
    
    fp = _fdopen( hConHandle, "r" );
    *stdin = *fp;
    setvbuf( stdin, NULL, _IONBF, 0 );
    
    // redirect unbuffered STDERR to the console
    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    
    fp = _fdopen( hConHandle, "w" );
    *stderr = *fp;
    setvbuf( stderr, NULL, _IONBF, 0 );
    
    // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
    // point to console as well
    ios::sync_with_stdio();
    

    Sample from: http://cygwin.com/ml/cygwin/2004-05/msg00215.html

    The problem with your WinMain call is that windows already has forked out your process so the calling cmd.exe console will have returned from your .exe already and proceed with the next command. To prevent that you can call your exe with start /wait myexe.exe This way you also get the return value of your app and you can check it with %errorlevel% as usual.

    If there is a way to prevent that process forking with subsystem windows please let me know.

    Hope this helps.

提交回复
热议问题