NO

Author Topic: Command Line Arguments for win32.exe  (Read 9871 times)

EdPellesC99

  • Guest
Command Line Arguments for win32.exe
« on: September 12, 2011, 04:31:20 AM »
This may be a dumb question, but is it possible to accept arguments from the command line in a win32.exe?

I have never run across any info on this.

I have never thought about it, until I wondered how a small editor I downloaded ran.

If it is not possible in C, then it must be possible in C++ (as I think the small editor was coded in C++).

I realize this is wacky, and I hate to ask.....because I am 99.99% sure that only the console app can take args in C....,

But .........I've only racked up one dumb award this week !

Tx, Ed



CommonTater

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #1 on: September 12, 2011, 04:37:11 AM »
This may be a dumb question, but is it possible to accept arguments from the command line in a win32.exe?

Yep, sure is... every file that is opened by association is opened with command line arguments giving the filename.

For console mode use...  int main (int argc, char *argv[]) ... the first is the number of parameters, the second is an array of strings each holding one parameter. 

For GUI code  use the lpCmdLine parameter of WinMain()

Either way you can use  GetCommandLine() which is available anywhere in the program, not just at the top of main.
http://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

Quote
I have never run across any info on this.

:)  Well, now you have :)

Quote
But .........I've only racked up one dumb award this week !

LOL... no worries... we all get them and there's lots more to come...
« Last Edit: September 12, 2011, 04:42:38 AM by CommonTater »

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: Command Line Arguments for win32.exe
« Reply #2 on: September 12, 2011, 06:16:42 AM »
Code: [Select]
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

int __cdecl WinMainCRTStartup(void)
{
char *lpszCmdLine, *pChar;

pChar = GetCommandLine();
if (*pChar == '"') {
pChar++;
while (*pChar && *pChar != '"')
pChar++;
pChar++;
} else {
while (*pChar && *pChar != ' ')
pChar++;
}
if (*pChar <= ' ')
pChar++;
lpszCmdLine = pChar;
MessageBox(0, lpszCmdLine, 0, MB_OK);
ExitProcess(0);
}
Silly example using msvcrt.dll
Code: [Select]
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#pragma comment (lib, "msvcrt.lib")

int __cdecl WinMainCRTStartup(void)
{
int __cdecl __getmainargs(int*, char***, char***, int, int*);

int    argc;
char** argv;
char** env;
int    new_mode = 0;

__getmainargs(&argc,&argv,&env,0,&new_mode);
MessageBox(0, argv[0], 0, 0);
if (argc>1) {
MessageBox(0, argv[1], 0, 0);
}
ExitProcess(0);
}
« Last Edit: September 12, 2011, 07:58:44 AM by timovjl »
May the source be with you

EdPellesC99

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #3 on: September 12, 2011, 06:02:24 PM »
Thanks much u2,

Wow that is powerful !  8)

I had this little editor win32.exe .... it did accept a file as a parameter.
However (it is a black box to me ... no source), I wrote a win32.exe that reliably positioned and sized the editor on my screen.

I wanted to have the Action Verb in Folder options for Open (on a text file) be:
"C:\Program Files\Tools\EdrunsLittleEditor.exe" "%".

So I realized I had no way to feed the parameter to the actual editor through my "Position and Size" program !

Then I wondered how the little box program took arguments....


Thanks so much Timo and Tater,

Code works like a champ and gives me a jump start on playing with this new power (I could be dangerous) !

.... Ed

CommonTater

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #4 on: September 12, 2011, 06:47:08 PM »
I wanted to have the Action Verb in Folder options for Open (on a text file) be:
"C:\Program Files\Tools\EdrunsLittleEditor.exe" "%".

Not trying to be overly picky, but that should be
"C:\Program Files\Tools\EdrunsLittleEditor.exe" "%1"

Besides editors are so easy to write, you could easily do the whole job yourself... All you'd really be doing is adding a parent window and some menus, maybe a toolbar, around a Windows EDIT control...

If you'd like a step by step tutorial on Windows API, here's a good place to start...
http://www.winprog.org/tutorial/





EdPellesC99

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #5 on: September 13, 2011, 12:26:47 AM »
too much in a hurry !

I've got it working like a champ already!


Making an editor might be a nice learning project, but for now I just want a little mini one to use as a scratch pad.

I am playing with win32pad.

SavageEd.exe is great, ....smaller even, done with Assembly and the source is available, but it will not let me position the window on the screen!


Tx Tater,
Ed


CommonTater

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #6 on: September 13, 2011, 12:31:17 AM »
too much in a hurry !

I've got it working like a champ already!


Making an editor might be a nice learning project, but for now I just want a little mini one to use as a scratch pad.

I am playing with win32pad.

SavageEd.exe is great, ....smaller even, done with Assembly and the source is available, but it will not let me position the window on the screen!


Tx Tater,
Ed

Hey a simple scratch pad... easy stuff....

Code: [Select]
/*

Tiny Unicode Editor Example

*/
// for the compiler
#define UNICODE
#define _UNICODE
#define WIN32_DEFAULT_LIBS
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0502
#define _X86_

// Windows headers
#include <windows.h>
#include <commdlg.h>

//  PellesC headers
#include <stdlib.h>
#include <wchar.h>
#include <tchar.h>

#define BOM_FLAG 0xFFFE


// Window handles
HWND      Wind[5]; 
HINSTANCE Inst;
TCHAR     FileName[MAX_PATH]; // filename when opened
BOOL      RevBytes = 0;


// save a file
void SaveToFile(void)
  { OPENFILENAME  ofn;        // filename struct
    HANDLE        fh;         // handle for opening files
    DWORD         fs;         // size of the data
    PTCHAR        fd;         // pointer to data
    // get the filename
    memset(&ofn,0,sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner    = Wind[0];
    ofn.hInstance    = Inst;
    ofn.lpstrFilter  = _T("All Files\0*.*\0\0");   
    ofn.lpstrFile    = FileName;
    ofn.nMaxFile     = MAX_PATH;
    ofn.lpstrTitle   = L"Save your work";
    ofn.Flags        = OFN_NONETWORKBUTTON |
                       OFN_HIDEREADONLY |
                       OFN_NOTESTFILECREATE |
                       OFN_OVERWRITEPROMPT;
    if (!GetSaveFileName(&ofn))
      return;
    // get unicode adjusted file size from edit control
    fs = (SendMessage(Wind[4],WM_GETTEXTLENGTH,0,0) * sizeof(TCHAR));
    if (fs < 1)
      return;
    // create text buffer
    fd = malloc(fs);
    // get the text from the control
    SendMessage(Wind[4],WM_GETTEXT,fs,(LPARAM)fd);
    // open the file
    fh = CreateFile(FileName,GENERIC_WRITE,0,NULL,
                            CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL |
                            FILE_FLAG_WRITE_THROUGH,NULL);
    // save the file
    if (fh != INVALID_HANDLE_VALUE)
      { WriteFile(fh,fd,fs,&fs,NULL);
        CloseHandle(fh); }
    free(fd); }



// open a file
void OpenFromFile(void)
  { OPENFILENAME  ofn;        // filename struct
    HANDLE        fh;         // handle for opening files
    DWORD         fs;         // size of the data
    PTCHAR        fd;         // pointer to data
    // get the filename
    memset(&ofn,0,sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner    = Wind[0];
    ofn.hInstance    = Inst;
    ofn.lpstrFilter  = L"All Files\0*.*\0\0";   
    ofn.lpstrFile    = FileName;
    ofn.nMaxFile     = MAX_PATH;
    ofn.lpstrTitle   = L"Open a file";
    ofn.Flags        = OFN_NONETWORKBUTTON |
                       OFN_HIDEREADONLY |
                       OFN_NOTESTFILECREATE |
                       OFN_OVERWRITEPROMPT;
    if (!GetOpenFileName(&ofn))
      return;
    // open the file
    fh = CreateFile(FileName,GENERIC_READ,FILE_SHARE_READ,NULL,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,NULL);
    if (fh == INVALID_HANDLE_VALUE)
      { MessageBox(Wind[0],L"Error opening the file",L"OOPS!",0);
        return; }
    // get the file size
    fs = GetFileSize(fh,NULL) + sizeof(TCHAR);
    // create text buffer
    fd = malloc(fs);
    // clear to 0
    memset(fd,0,fs);
    // read from disk 
    ReadFile(fh,fd,fs,&fs,NULL);
    // close the file
    CloseHandle(fh);
    // put the text in the control
    SendMessage(Wind[4],WM_SETTEXT,fs,(LPARAM)fd);
    free(fd); }



// resize the window
VOID ResizeWindow(LPARAM lParm)
  { MoveWindow(Wind[4],60,2,LOWORD(lParm) - 62,HIWORD(lParm) - 4,1); }



// Message Loop
LRESULT CALLBACK MsgProc(HWND wnd,UINT msg,WPARAM wparm,LPARAM lparm)
  { switch (msg)
      { case WM_COMMAND :
          switch (LOWORD(wparm))
            { case 1001 :
                OpenFromFile();
                return 0;
              case 1002 :
                SaveToFile();
                return 0;
              case 1003 :
                PostMessage(Wind[0],WM_CLOSE,0,0);
                return 0;
              default :
                return DefWindowProc(wnd,msg,wparm,lparm); }
        case WM_SIZE  :
          ResizeWindow(lparm);
          return 0;
        case WM_CLOSE :         // close window
          DestroyWindow(Wind[0]); 
          return 0;
        case WM_DESTROY :       // NC Exit button
          PostQuitMessage(0);
          return 0;
        default :
          return DefWindowProc(wnd,msg,wparm,lparm); } }


// create the window
VOID CreateMainWindow(void)
  { WNDCLASS  wc;
    // register App Class
    memset(&wc,0,sizeof(wc));
    wc.style          = CS_CLASSDC;
    wc.hInstance      = Inst;
    wc.hCursor        = LoadCursor(NULL,IDC_ARROW);
    wc.hbrBackground  = CreateSolidBrush(GetSysColor(COLOR_3DFACE));
    wc.lpfnWndProc    = &MsgProc;
    wc.lpszClassName  = L"TINY_UNICODE";
    RegisterClass(&wc);

    // create the main window
    Wind[0] = CreateWindowEx( WS_EX_CONTROLPARENT,
                    L"TINY_UNICODE",L"Tiny Unicode Editor",
                    WS_OVERLAPPEDWINDOW,
                    CW_USEDEFAULT,0,500,300,NULL,NULL,Inst,NULL);
    // buttons
    Wind[1] = CreateWindow(L"BUTTON",L"Open",
                    WS_CHILD | WS_VISIBLE | BS_FLAT,
                    2,2,50,25,Wind[0],(HMENU) 1001,Inst,NULL);
    Wind[2] = CreateWindow(L"BUTTON",L"Save",
                    WS_CHILD | WS_VISIBLE | BS_FLAT,
                    2,30,50,25,Wind[0],(HMENU) 1002,Inst,NULL);
    Wind[3] = CreateWindow(L"BUTTON",L"Quit",
                    WS_CHILD | WS_VISIBLE | BS_FLAT,
                    2,60,50,25,Wind[0],(HMENU) 1003,Inst,NULL);
    // edit window
    Wind[4] = CreateWindowEx(WS_EX_CLIENTEDGE,L"EDIT",NULL,
                    WS_CHILD | WS_VISIBLE |
                    ES_MULTILINE,
                    60,2,200,200,Wind[0],NULL,Inst,NULL); 
    UpdateWindow(Wind[0]);
    ShowWindow(Wind[0],SW_SHOWNORMAL);    }

         
// Program Entry Procedure
int WINAPI WinMain(HINSTANCE hinst, HINSTANCE pinst, LPSTR cmdl, int show)
  { MSG wmsg;
    // save instance handle
    Inst =    hinst;   
    // make the window
    CreateMainWindow();
    // dispatch window messages
    while (GetMessage(&wmsg,NULL,0,0))
      { TranslateMessage(&wmsg);
        DispatchMessage(&wmsg); }

    return 0; }

You should be able to cut and past this into a project and then dissect it to make improvements, easily enough...
« Last Edit: September 13, 2011, 12:33:45 AM by CommonTater »

EdPellesC99

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #7 on: September 13, 2011, 04:58:03 PM »
Interesting, very.

Tx Tater,

This is set up to be a unicode text only editor.

In my simpleton programming, I have stayed ansi. I guess I am not very "global" or maybe "hip".
It just seemed to add another level of unnecessary complexity to me the learner.

Maybe this is an illusion,
I have no idea if others have ever felt this way.

It compiles nicely, and I will keep and go back to this ......to learn.

I have looked at similar projects from  Petzold's book, yours has a new button/type arrangement that I haven't seen before.

Good grief I think you could spend two lifetimes just getting better at c and c use with the win32.

.... Sometimes it makes me feel pretty small (even smaller than I am !)..........  :)

The honest truth is, if you try to learn C and the api in Pelles C (no better way), it is both fun and humbling !

You aren't trying very hard if you think you are getting to be an expert !

Yikes, if that isn't the truth.
 
But it has really been satisfying, to make progress of sorts over the months...

One day I will work your code, into something I am trying to do ..... for sure.

Tx,
Ed




CommonTater

  • Guest
Re: Command Line Arguments for win32.exe
« Reply #8 on: September 14, 2011, 01:51:25 AM »
Interesting, very.

Tx Tater,

This is set up to be a unicode text only editor.

Actually if you comment out the #defines for unicode it should compile as ansi ... maybe as is, but certainly with only minor fixups.


Quote
Maybe this is an illusion,
I have no idea if others have ever felt this way.

Frankly I think unicode is a pain in the male frontal parts... But if you're going to write anything that leaves your own hard disk these days it has to at least accept unicode text as inputs.