Partage
  • Partager sur Facebook
  • Partager sur Twitter

[winAPI] Problème ... ou plutot comment faire ?

volets, conséquences de ceux ci et fonctions de dessins

    8 février 2006 à 19:07:41

    Voila mon problème : j'ai créé avec l'aide de cours sur ce sujet un NotePad à moi :p en winAPI ... Seulement j'aimerais qu'ils soit plutot ... comme un couteau suisse :-° en effet je compte faire plusieurs cas de fenetre principale avec respectivement "Texte", "Dessin" et peut etre lecteur de musique (WAV)... choisis dans la barre d'outils (un genre de "toggle to Texte" ou "Dessin" ) :j'ai réussi le texte mais en fait j'ai plusieurs problèmes :
    - j'aimerais que "Sauvegarder" soit d'extension différente selon le cas choisi :( - ensuite j'aimerais quelques codes pour le dessin : genre que l'utilisateur puisse faire des traits, des cercles et des rectangles... basique quoi ! ^^:o
    "C'est tout" o_O ... voici mon code. Si vous avez des améliorations (surtout comique .. j'aime ca ! :p ) dites le moi !

    fichier "resource.rc" :
    #include <windows.h>
    #include "header1.h"

    1 ICON C:\Utils\Programmation\Dev-Cpp\Projects\Greg's_NotePad\Notepad.ico
    2 ICON C:\Utils\Programmation\Dev-Cpp\Projects\Greg'
    s_NotePad\Folder.ico
    3 ICON C:\Utils\Programmation\Dev-Cpp\Projects\Greg's_NotePad\Crazy.ico

    MyMenu MENU
    BEGIN
          POPUP "Fichier"
                BEGIN
                  MENUITEM "&Nouveau...", IDM_NEW
                  MENUITEM "&Ouvrir...", IDM_OPEN
                  MENUITEM "&Sauvegarder", IDM_SAVE
                  MENUITEM SEPARATOR
                  MENUITEM "&Quitter", IDM_QUIT
                END
          POPUP "Affichage"
                BEGIN
                  MENUITEM "&Police...", IDM_FONT
                  MENUITEM "&Couleur...", IDM_TEXTCOLOR
                END
          POPUP "Aide"
                BEGIN
                  MENUITEM "A propos", IDM_ABOUT
                END
    END

    Dialog1 DIALOG
         60, 60, 240, 85
               STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
                                                                 CAPTION "A propos !"
    BEGIN
        DEFPUSHBUTTON "J'
    men fous !", IDOK, 80, 60, 72, 12
        ICON 3, -1, 20, 20, 32, 32
        LTEXT "
    Cette application Windaube est un modeste programme à visée récréative ! \n Con&#231;u par :                    >[¤GrÊgg¤]<",
        -1, 50, 18, 180, 30
    END


    fichier main.c :
    #include <windows.h>
    #include "header1.h"

    UINT Nature;
    UINT Dessin;
    UINT Texte;

    HINSTANCE hinst;
    HWND hwnd;
    HWND edit1;
    BOOL EditNotChg = TRUE;

    BOOL APIENTRY Dialog2Proc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam);
    LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM); //prototype !
    BOOL APIENTRY Dialog1Proc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam);

    int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,
                                                    LPSTR lpCmdLine, int nCmdShow)
    // winMAIN
    {
            /* Initialisations :*/
       
        MSG msg; // Messages systeme
        WNDCLASS wc; // Classe de fenêtre "mère"

        hinst = hinstance;
        // Définition de la classe wc :
        wc.style = 0 ; // Style de fenêtre (défault)
        wc.lpfnWndProc = MainWndProc; // procédure de fenêtre
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = NULL; // handle d'instance (sorte de moule) fourni par winMAIN
        wc.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(2)); // icône n°2 dans la resource
        wc.hCursor = LoadCursor(NULL, IDC_ARROW); // style curseur (ici fleche normale)
        wc.hbrBackground = NULL; // couleur fond de fenêtre
        wc.lpszMenuName"MyMenu"; // Nom du menu si il y a ... ou deuxieme méthode (utilisée)
        wc.lpszClassName = "MaWinClass"; // pointeur sur nom de la classe

        if(!RegisterClass(&wc)) return FALSE; // Si la sauvegarde de wc plante, retourner FALSE

        hwnd = CreateWindow("MaWinClass", "Greg's NotePad", WS_OVERLAPPEDWINDOW,
                                       CW_USEDEFAULT, CW_USEDEFAULT, 400, 300,
                                                       NULL, NULL, hinstance, NULL);
        /* ci dessus on crée la fenêtre principale de classe "mawinclasse" (wc), de nom greg's program,
        de style overlappedwindow ( défault), avec des positions défault, ayant comme taille 400*300 et ayant Menu,
        et enfin instance.*/

        if (!hwnd)  return FALSE;
        // si ca plante retourner FALSE
        ShowWindow(hwnd, nCmdShow); // On l'affiche

        while (GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg); // Systeme de transmission des ùessages systeme
            DispatchMessage(&msg);
        }
        return msg.wParam;
    }
    /******************************************************************************/

    BOOL APIENTRY Dialog1Proc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
    {
        switch (uMsg)
        {
          case WM_INITDIALOG:

             return TRUE;

          case WM_COMMAND:
             if (LOWORD(wParam) == IDCANCEL || LOWORD(wParam) == IDOK)
                    {
                       EndDialog(hDlg,0);
                       return TRUE;
                    }

          default:
             return FALSE;
        }
    }

    LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        static HFONT hFont;
        static LOGFONT lf;
        static HBRUSH EditBrush;
        static COLORREF BkEditcolor;
        static COLORREF TextColor = 0;
        static HWND edit1;
        static BOOL EditNotChg = TRUE;
        switch (uMsg)
        {
            case WM_CREATE:
                {
                 HFONT hFont;
                 Nature = ID_Texte;
                 edit1 = CreateWindow("edit", "T'es un gros noeud !",
                   WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_WANTRETURN | WS_VSCROLL,
                                                0, 0, 0, 0, hwnd, NULL, hinst, NULL);
                   // création de la zone de texte fille de la fenêtre mere
                 BkEditcolor = GetSysColor(COLOR_WINDOW);
                 EditBrush = CreateSolidBrush(BkEditcolor);
                 hFont = (HFONT)GetStockObject(ANSI_FIXED_FONT);
                 SendMessage(edit1,WM_SETFONT,(UINT)hFont,TRUE);
                 SendMessage(edit1, EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN,
                                                                    MAKELONG(5, 5));

                 return 0;
                }

            case WM_CLOSE:
                if(EditNotChg ||
                   MessageBox(hwnd,"Le texte a été modifié. Voulez-vous vraiment quitter ?"
                                ,"Quitter ?",MB_YESNO | MB_ICONQUESTION ) == IDYES)
                                                                DestroyWindow(hwnd);
                // assez précis pour se apsser de commentaires ...
                return 0;

            case WM_COMMAND:
                if(LOWORD(wParam) == IDM_QUIT) PostMessage(hwnd, WM_CLOSE,0,0);
                if(HIWORD(wParam) == EN_CHANGE) EditNotChg = FALSE; //idem
                if(LOWORD(wParam) == IDM_OPEN)
                { OPENFILENAME ofn; // on crée cette variable
                  char szFile[MAX_PATH] = {0}; // initialise un tableau de taille MAX_PATH (s'appelant szFile
                 
                  ZeroMemory(&ofn, sizeof(OPENFILENAME)); // on met tt à zéro (structure)
                  ofn.lStructSize = sizeof(OPENFILENAME); //recoit taille de structure
                  ofn.hwndOwner = hwnd; // handle de fenêtre mère
                  ofn.lpstrFile = szFile; // récupération du chemin et nom de fichier dans tableau du début
                  ofn.nMaxFile = MAX_PATH; // taille du tableau de caractere recevant nom de fichier
                  ofn.lpstrFilter = "Fichier texte\0*.txt\0Fichier source C\0*.c\0Fichier source C++\0*.cpp\0"; //filtres ( avec 0 comme séparateur entre
                  // les extentions et descriptions
                  ofn.nFilterIndex = 1; // index des filtres ( 1 pour défault )
                  ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
                  // --> Flags influent sur aspect et fonctions
                            if(GetOpenFileName(&ofn) == TRUE) // si (TRUE) on a appuyé sur "ouvrir" renvoie le tt
                              { HANDLE hf; //handle du fichier
                                DWORD FileSize,nbcharRead ;
                                CHAR *buffer; // tableau-buffer
                                hf = CreateFile(szFile, GENERIC_READ, 0,NULL, // ouvre le fichier
                                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // et retourne le handle du fichier
                                FileSize = GetFileSize(hf, NULL); // bon...
                                buffer = (PCHAR)LocalAlloc(LMEM_FIXED, FileSize+1); // rajoute un octet à buffer pour caractere 0
                                ReadFile(hf, buffer, FileSize, &nbcharRead, NULL) ; // balance le contenu du fichier dans buffer
                                buffer[FileSize] = 0; // on rajoute 0 à la fin pour en faire une string
                                SendMessage(edit1, WM_SETTEXT, 0, (LPARAM)buffer); // et affiche le texte dans notre edit1
                                LocalFree(buffer); // on congédie le buffer ;D
                                CloseHandle(hf); // et on ferme le handle ... fini !
                              }
                  }
                 
                  if(LOWORD(wParam) == IDM_FONT)
                  {
                    CHOOSEFONT cf;
                    ZeroMemory(&cf, sizeof(CHOOSEFONT));
                    cf.lStructSize = sizeof (CHOOSEFONT);
                    cf.hwndOwner = hwnd;
                    cf.lpLogFont = &lf;
                    cf.Flags = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT;

                    if (ChooseFont(&cf))
                     {
                        DeleteObject(hFont);
                        hFont = CreateFontIndirect(&lf);
                        SendMessage(edit1,WM_SETFONT,(UINT)hFont,TRUE);
                     }
                  }
                  if(LOWORD(wParam) == IDM_SAVE)
                  {
                    OPENFILENAME ofn;
                    CHAR szFile[260]={0};

                    ZeroMemory(&ofn, sizeof(OPENFILENAME));
                    ofn.lStructSize = sizeof(OPENFILENAME);
                    ofn.hwndOwner = hwnd;
                    ofn.lpstrFile = szFile;
                    ofn.nMaxFile = sizeof(szFile);
                    ofn.lpstrFilter =
                               "Fichier texte\0*.txt\0Fichier source C\0*.c\0Fichier source C++\0*.cpp\0";
                    ofn.nFilterIndex = 1;
                    ofn.Flags =
                           OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
                    if (GetSaveFileName(&ofn)==TRUE)
                     {
                        HANDLE hf;
                        DWORD FileSize,nbcharRead ;
                        char *buffer;
                        FileSize = GetWindowTextLength(edit1);
                        buffer = (char*)LocalAlloc(LMEM_FIXED, FileSize+1);
                        GetWindowText(edit1, buffer, FileSize+1);
                        hf = CreateFile(szFile, GENERIC_WRITE, 0,NULL,
                                        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
                        WriteFile(hf, buffer, FileSize, &nbcharRead, NULL) ;
                        CloseHandle(hf);
                        LocalFree(buffer);
                     }
                  } /*if IDM_SAVE*/
                 
                  if(LOWORD(wParam) == IDM_TEXTCOLOR)
                  {
                        CHOOSECOLOR cc;
                        static COLORREF acrCustClr[16];

                        ZeroMemory(&cc, sizeof(CHOOSECOLOR));
                        cc.lStructSize = sizeof(CHOOSECOLOR);
                        cc.hwndOwner = hwnd;
                        cc.lpCustColors = NULL;
                        cc.lpCustColors = (LPDWORD) acrCustClr;
                        cc.rgbResult = TextColor;
                        cc.Flags = CC_FULLOPEN | CC_RGBINIT;
                       
                        if (ChooseColor(&cc)==TRUE)
                            {
                              TextColor = cc.rgbResult;
                              PostMessage(edit1,WM_SETREDRAW,TRUE,0);
                            }
                  } /*if IDM_TEXTCOLOR*/
                 
                  if(LOWORD(wParam) == IDM_NEW)
                    {if(EditNotChg ||
                      MessageBox(hwnd,"Le texte a été modifié. Voulez-vous vraiment recommencer ?"
                                ,"Nouveau ?",MB_YESNO | MB_ICONQUESTION ) == IDYES)
                          {SendMessage(edit1,WM_SETTEXT,0,(LPARAM)"");
                    EditNotChg = TRUE;}
                    }
                if(LOWORD(wParam) == IDM_ABOUT)
                         DialogBox(hinst, "Dialog1", hwnd, (DLGPROC)Dialog1Proc);
                return 0;
           
            case WM_CTLCOLOREDIT:
                if((HWND)lParam == edit1)
                  {
                   SetTextColor((HDC)wParam, TextColor);
                   SetBkColor((HDC)wParam, BkEditcolor);
                   return EditBrush;
                  }
                break;

            case WM_SIZE:
                MoveWindow(edit1, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE);
                 //adapte la taille de zone de texte en fonction de fenêtre mere
                 return 0;           

            case WM_DESTROY: // si on ferme la fenêtre mere, ...
                MessageBox(NULL, "En voulant se fermer, l'application <Greg's NotePad> s'est méchamment vautrée : votre ordinateur pourrait y laisser sa pomme. Préparez l'extincteur !", "Erreur...", 0); // on affiche ca !
                PostQuitMessage(0); // et on quitte
                return 0;

            default:
                return DefWindowProc(hwnd, uMsg, wParam, lParam); // si aucun message n'est envoyé on fait rien ...
        }
    }



    et enfin le fichier "Header1.h" :
    #define IDM_QUIT 1
    #define IDM_OPEN 2
    #define IDM_FONT 3
    #define IDM_SAVE 4
    #define IDM_TEXTCOLOR 5
    #define IDM_NEW 6
    #define IDM_ABOUT 7
    #define ID_RB1 101
    #define ID_RB2 102
    #define ID_OK 10

    #define ID_Dessin 1
    #define ID_Texte 2


    Bon voila j'espere que vous m'avez compris et que vous vous etes pas endormis !
    • Partager sur Facebook
    • Partager sur Twitter

    [winAPI] Problème ... ou plutot comment faire ?

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown