以下のサンプルでは、Windows APIのメッセージボックス機能(MessageBox関数)を使ってコマンドライン引数を2種類の方法で表示させている。(OKボタンを持つメッセージボックスが2回連続表示されます)
Window APIのコマンドライン引数であるlpCmdLineとコマンドライン引数を戻り値に持つ関数GetCommandLine()の両方を使って違いを確認している。
サンプルコード
get_commandline.c
/* WindowsAPI: コマンドライン引数を返す */
#include <windows.h>
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
){
/* WINAPIの第3引数から得る場合 */
MessageBox(NULL, lpCmdLine, TEXT("GetCommandLineテスト"), MB_ICONINFORMATION);
/* GetCommandLine関数から得る場合 */
MessageBox(NULL, GetCommandLine(), TEXT("GetCommandLineテスト"), MB_ICONINFORMATION);
return 0;
}
gccコンパイラでコンパイルする場合は、-mwindows オプションをつけて
gcc -o get_commandline get_commandline.c -mwindows
としてコンパイルしてください。
実行イメージ
コマンドプロンプトから単純な文字列を引数に指定して実行した場合はこんな感じ。

実行結果(lpCmdLineを表示)

引数のみが表示された。
実行結果(GetCommandLine関数の戻り値を表示)

GetCommandLine関数では、実行プログラム本体の名称も引数に含まれている。
ドラッグ&ドロップによる実行
実行ファイルに適当なファイルをドラッグ&ドロップしても引数として扱われる。

実行結果(lpCmdLineを表示)
ファイルをドラッグ&ドロップするとパス名も含めてコマンドライン引数として返される。

実行結果(GetCommandLine関数の戻り値を表示)
更にGetCommandLine関数の戻り値では、実行プログラム名、引数ともにパス名が含まれている。

GetCommandLine関数の方が使い勝手が良さそうだ。
解説
Windows APIのプログラムは、第3引数がコマンドライン引数となっている。
ただし、C言語の
int main(int argc, char *argv[])
{
/* 省略 */
}
のように引数の要素数(argc)と実際の文字配列へのポインタ(argv)という形で分けて得られるのではなく、一つの文字列へのポインタ(lpCmdLine)として返される。
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
){
/* 省略 */
}
こちらのサイトを参考にさせて頂いた。
コマンドライン引数
コメント