Windows unicode commandline argv

2020-02-25 23:46发布

问题:

So getting into the new millenia I rewrote my c++ code with:

int main(int argc, wchar_t **argv)

If built with either Unicode or MBCS options then when the app is run with a commandline arg, either directly or by dbl-click the filenames passed to argv[] are unreadable = in some mixture of chinese fonts.

Thanks for the comments - I will try and summaris(z)e them here for the search engine.

  1. wmain(int argc,char **argv) can only be used for a commandline (subsystem:console) app

  2. int winMain(int argc, wchar_t **argv) works for a gui (subsystem:windows) but the gui replaces it with it's own entry point. In the case of Qt this doesn't work

    qtmaind.lib(qtmain_win.obj) : error LNK2019: unresolved external symbol _main referenced in function _WinMain@16

The solution seems to be use main(int arc,char **argv) or main(int argc,wchar_t**argv) but ignore the argv. Then call QApplication with argv or NULL - the argv is ignored as Qt internally calls GetCommandLine().
Then use app.arguments to return the parsed arguments.
These can then be converted back into wchar with Qt's string functions if needed.

 QApplication app(argc, (char**)argv);  or  QApplication app(argc,NULL);  
 QStringList args = app.arguments();

Sorry I didn't originally flag this Qt because I didn't think that was relevant.
If somebody wants to edit this to also include how to do this in MFC - please do.

回答1:

You need to name your entry point wmain: http://msdn.microsoft.com/en-us/library/fzc2cy7w(VS.80).aspx



回答2:

You can use GetCommandLine function for that purpose.



回答3:

Try this:

#include <tchar.h>

int _tmain( int argc, TCHAR **argv )
{
  return 0;
}

_tmain is defined as wmain when compiled with the UNICODE option and as main when compiled with the MBCS option.