Results 1 to 5 of 5
  1. #1
    Join Date
    Aug 2004
    Location
    little rock arkansas
    Posts
    3,482

    Windows Api Getting and setting text in an edit box

    I am having an issue with an Item Editor i am developing with the windows API

    every time i try to load or save string data to a binary file all i get is trash when i load it back in

    i have tried several things to get the data to load properly and i cannot figure it out
    can someone take a look at this for me please
    i can load all the numerical data and read it back it is the string for the name that i am having the issue with

    main.cpp
    Code:
    #include <windows.h>
    #include <stdio.h>
    #include "resource.h"
    #include <string>
    using namespace std;
    
    class Equipment
    {
    
    public:
    	Equipment(  );
    	~Equipment(  );
    	int GetItemID(  ) const;
    	void SetItemID( int value );
    	string GetName(  ) const;
    	void SetName( string value );
    	int GetItemLevel(  ) const;
    	void SetItemLevel( int value );
    	int GetPhysicalAttack(  ) const;
    	void SetPhysicalAttack( int value );
    protected:
    	int m_ItemID;
    	string m_Name;
    	int m_ItemLevel;
    	int m_PhysicalAttack;
    
    };
    
    
    // Application variables ////////////////////////////////////////////
    HWND g_hWnd;                   // Window handle
    char g_szClass[] = "EQUIPMENTEDITOR";  // Class name
    
    OPENFILENAME g_ofn;            // Open/Save dialog data
    char g_MILFile[MAX_PATH];      // Filename for item files
    const int itemMax = 10;        // Item list
    Equipment g_Items1[itemMax]; 
    long  g_EditItem;              // Item to modify
    
    // Application prototypes ///////////////////////////////////////////
    int  PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow);
    long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
    BOOL CALLBACK ModifyDialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
    
    BOOL UpdateEntry(HWND hWnd, long ItemNum);
    BOOL LoadItems(char *Filename);
    
    
    BOOL LoadMIL()
    {
      // Setup the open dialog info
     g_ofn.hwndOwner   = g_hWnd;
      g_ofn.lpstrFile   = g_MILFile;
      g_ofn.lpstrTitle  = "Load Equipment File";
      g_ofn.lpstrFilter = "Equipment Files (*.itm)\0*.itm\0All Files (*.*)\0*.*\0\0";
      g_ofn.lpstrDefExt = "itm";
    
      // Ask for filename
      if(!GetOpenFileName(&g_ofn))
        return FALSE;
    
      // Load the file and return result
      if(LoadItems(g_MILFile) == FALSE) {
        MessageBox(g_hWnd, g_MILFile, "Unable to open file.", MB_OK);
        return FALSE;
      }
      return TRUE;
    }
    
    BOOL SaveMIL()
    {
      FILE *fp;
      long i;
    
      // Setup the open dialog info
      g_ofn.hwndOwner   = g_hWnd;
      g_ofn.lpstrFile   = g_MILFile;
      g_ofn.lpstrTitle  = "Load Equipment File";
      g_ofn.lpstrFilter = "Equipment Files (*.itm)\0*.itm\0All Files (*.*)\0*.*\0\0";
      g_ofn.lpstrDefExt = "itm";
      // Ask for filename
      if(!GetSaveFileName(&g_ofn))
        return FALSE;
    
      // Open filename for saving
      if((fp=fopen(g_MILFile, "wb")) == NULL)
        return FALSE;
    
       for(i=0;i<itemMax;i++)
    	   fwrite(&g_Items1[i], sizeof(Equipment),1, fp);
    
      // Close file and return success
      fclose(fp);
      
      return TRUE;
    }
    // Application //////////////////////////////////////////////////////
    int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow)
    {
      WNDCLASS wc;
      MSG      Msg;
    
      // Register window class
      wc.style         = CS_HREDRAW | CS_VREDRAW;
      wc.lpfnWndProc   = WindowProc;
      wc.cbClsExtra    = 0;
      wc.cbWndExtra    = DLGWINDOWEXTRA;
      wc.hInstance     = hInst;
      wc.hIcon         = LoadIcon(hInst, IDI_APPLICATION);
      wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
      wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
      wc.lpszMenuName  = NULL;
      wc.lpszClassName = g_szClass;
      RegisterClass(&wc);
    
      // Create the dialog box window and show it
      g_hWnd = CreateDialog(hInst, MAKEINTRESOURCE(IDD_EDIT), 0, NULL);
      UpdateWindow(g_hWnd);
      ShowWindow(g_hWnd, nCmdShow);
    
      // Force a load of items from default.mil
      LoadItems("Default.itm");
    
      // Message loop
      while(GetMessage(&Msg, NULL, 0, 0)) 
      {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
      }
    
      // Clean up
      UnregisterClass(g_szClass, hInst);
    
      return 0;
    }
    
    LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
      int Selection;
      char Text[256];
    
      switch(uMsg) {
        case WM_COMMAND:
          switch(LOWORD(wParam)) 
    	  {
            // Load a MIL file
            case IDC_LOAD: 
              LoadMIL();
              break;
    
            // Save a MIL file
            case IDC_SAVE: 
              SaveMIL();
              break;
    
    
            // Edit an entry
            case IDC_ITEMS:
              if(HIWORD(wParam) != LBN_DBLCLK)
                break;
            case IDC_EDIT:
              // See if an item was selected
              if((Selection = SendMessage(GetDlgItem(g_hWnd, IDC_ITEMS), LB_GETCURSEL, 0, 0)) == LB_ERR)
                break;
    
              // Setup the item to edit
              g_EditItem = Selection;
    
              // Call the modify item dialog
              DialogBox(NULL, MAKEINTRESOURCE(IDD_MODIFY), hWnd, ModifyDialogProc);
    
              // Update item
              SendMessage(GetDlgItem(g_hWnd, IDC_ITEMS), LB_DELETESTRING, Selection, 0);
    		  sprintf(Text, "%5lu: %s", Selection, g_Items1[Selection].GetName());
              SendMessage(GetDlgItem(g_hWnd, IDC_ITEMS), LB_INSERTSTRING, Selection, (LPARAM)Text);
              break;
          }
          break;
        
        case WM_CREATE:
          // Initialize the save/load dialog box info
          ZeroMemory(&g_ofn, sizeof(OPENFILENAME));
          g_ofn.lStructSize = sizeof(OPENFILENAME);
          g_ofn.nMaxFile = MAX_PATH;
          g_ofn.nMaxFileTitle = MAX_PATH;
          g_ofn.Flags = OFN_HIDEREADONLY | OFN_CREATEPROMPT | OFN_OVERWRITEPROMPT;
    
          // Set default MIL filename
          strcpy(g_MILFile, "Default.itm");
    
          break;
    
        case WM_DESTROY:
          PostQuitMessage(0);
          break;
    
        default: return DefWindowProc(hWnd, uMsg, wParam, lParam);
      }
    
      return 0;
    }
    
    BOOL CALLBACK ModifyDialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
    
      char Text[32];
    
      string test= "";
      switch(uMsg)
      {
    		case WM_INITDIALOG:
    		  // Return an error if there's no item to modify
    		  if(g_EditItem > 9999) {
    			EndDialog(hWnd, FALSE);
    			return FALSE;
    		  }
    
    
          // Item Number
          sprintf(Text, "%lu", g_EditItem);
          SetWindowText(GetDlgItem(hWnd, IDC_NUM), Text);
    
    
    //
    sprintf(Text, "%ls", g_Items1[g_EditItem].GetName());
    SetWindowText(GetDlgItem(hWnd, IDC_NAME),Text);
    
    sprintf(Text, "%li", g_Items1[g_EditItem].GetItemLevel());
    SetWindowText(GetDlgItem(hWnd, IDC_ITEMLEVEL), Text);
    
    sprintf(Text, "%li", g_Items1[g_EditItem].GetPhysicalAttack());
    SetWindowText(GetDlgItem(hWnd, IDC_PHYSICALATTACK), Text);
    
    
    
          return TRUE;
    
        case WM_COMMAND:
          switch(LOWORD(wParam)) 
    	  {
    			case IDC_OK: 
    			  UpdateEntry(hWnd, g_EditItem);
    			  EndDialog(hWnd, TRUE);
    			  return TRUE;
    
    			case IDC_CANCEL: 
    			  EndDialog(hWnd, FALSE);
    			  return TRUE;
          }
          break;
      }
    
      return FALSE;
    }
    
    BOOL UpdateEntry(HWND hWnd, long ItemNum)
    {
    
      char Text[32];
      string mytest="";
      int i;
    
      int sz = 0;
    GetWindowText(GetDlgItem(hWnd, IDC_NAME),Text, 32);	
     sz = sizeof(Text);
    	for(i = 0; i < sz; i++)
    		mytest += Text[i];
    g_Items1[ItemNum].SetName( mytest );
    GetWindowText(GetDlgItem(hWnd, IDC_ITEMLEVEL), Text, 32);
    g_Items1[ItemNum].SetItemLevel( (int)atoi(Text) );
    
    GetWindowText(GetDlgItem(hWnd, IDC_PHYSICALATTACK), Text, 32);	
    g_Items1[ItemNum].SetPhysicalAttack( (int)atoi(Text) );
    
      return TRUE;
    }
    
    BOOL LoadItems(char *Filename)
    {
      FILE *fp;
      int i;
      char Text[32];
    
      // Open the file
      if((fp=fopen(Filename, "rb")) != NULL)
      {
    
        for(i=0;i<itemMax;i++)
    	{
          fread(&g_Items1[i],sizeof(Equipment),1, fp);
    	}
        // Close file 
        fclose(fp);
      }
    
      SendMessage(GetDlgItem(g_hWnd, IDC_ITEMS), LB_RESETCONTENT, 0, 0);
      for(i=0;i<itemMax;i++) {
    	sprintf(Text, "%5lu: %s", i, g_Items1[i].GetName());
        SendMessage(GetDlgItem(g_hWnd, IDC_ITEMS), LB_INSERTSTRING, i, (LPARAM)Text);
      }
    
      return TRUE;
    }
    
    int Equipment::GetItemID(  ) const
    {	return m_ItemID;
    }
    
    
    void Equipment::SetItemID( int value )
    {	m_ItemID = value;
    }
    
    string Equipment::GetName(  ) const
    {	return m_Name;
    }
    
    
    void Equipment::SetName( string value )
    {	m_Name = value;
    }
    
    int Equipment::GetItemLevel(  ) const
    {	return m_ItemLevel;
    }
    
    
    void Equipment::SetItemLevel( int value )
    {	m_ItemLevel = value;
    }
    
    int Equipment::GetPhysicalAttack(  ) const
    {
    	return m_PhysicalAttack;
    
    }
    void Equipment::SetPhysicalAttack( int value )
    {	m_PhysicalAttack = value;
    }
    
    
    Equipment::Equipment(  )
    {
    	 m_ItemID = 0;
    	 m_Name = "UNKOWN" ;
    	 m_ItemLevel = 1;
    	 m_PhysicalAttack = 1;
    }
    Equipment::~Equipment(  )
    {// TODO: Implement
    }
    resource.h
    Code:
    #ifndef IDC_STATIC
    #define IDC_STATIC (-1)
    #endif
    
    #define IDD_EDIT                                101
    #define IDD_MODIFY                              103
    #define IDC_ITEMS                               1006
    #define IDC_EDIT                                1007
    #define IDC_CLEAR                               1008
    #define IDC_NEW                                 1009
    #define IDC_SAVE                                1010
    #define IDC_LOAD                                1011
    #define IDC_NUM                                 1011
    #define IDC_NAME                                1034
    #define IDC_ITEMLEVEL                           1035
    #define IDC_PHYSICALATTACK                      1037
    #define IDC_CANCEL                              1058
    #define IDC_OK                                  1059
    resource.rc
    Code:
    #include <windows.h>
    #include <commctrl.h>
    #include <richedit.h>
    #include "resource.h"
    //
    // Dialog resources
    //
    LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
    IDD_EDIT DIALOG 0, 0, 263, 194
    STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU
    CAPTION "Master Equipment Editor by ostamo2"
    CLASS "EQUIPMENTEDITOR"
    FONT 8, "Ms Shell Dlg"
    {
        DEFPUSHBUTTON   "Load", IDC_LOAD, 200, 114, 50, 15
        PUSHBUTTON      "Save", IDC_SAVE, 200, 138, 50, 15
        LISTBOX         IDC_ITEMS, 5, 30, 185, 160, WS_TABSTOP | WS_VSCROLL | LBS_NOINTEGRALHEIGHT | LBS_SORT | LBS_NOTIFY
        PUSHBUTTON      "Edit", IDC_EDIT, 200, 35, 50, 15
        PUSHBUTTON      "Clear", IDC_CLEAR, 200, 61, 50, 15
        PUSHBUTTON      "New", IDC_NEW, 200, 88, 50, 15
        LTEXT           "Equipment List", IDC_STATIC, 5, 20, 50, 10, SS_LEFT
    }
    
    
    
    LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
    IDD_MODIFY DIALOG 0, 0, 339, 251
    STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU
    CAPTION "Modify Equipment"
    FONT 8, "Ms Shell Dlg"
    {
        LTEXT           "Item #", IDC_STATIC, 5, 10, 21, 8, SS_LEFT
        LTEXT           "#", IDC_NUM, 30, 10, 21, 8, SS_LEFT
        LTEXT           "Name", IDC_STATIC, 7, 27, 59, 8, SS_LEFT
        LTEXT           "ItemLevel", IDC_STATIC, 7, 45, 59, 8, SS_LEFT
        LTEXT           "PhysicalAttack", IDC_STATIC, 7, 81, 59, 8, SS_LEFT
    	EDITTEXT        IDC_PHYSICALATTACK, 85, 77, 46, 12, ES_AUTOHSCROLL
    	EDITTEXT        IDC_ITEMLEVEL, 85, 41, 46, 12, ES_AUTOHSCROLL
        EDITTEXT        IDC_NAME, 85, 23, 46, 12, ES_AUTOHSCROLL
        PUSHBUTTON      "Cancel", IDC_CANCEL, 181, 230, 46, 14
        PUSHBUTTON      "OK", IDC_OK, 248, 230, 46, 14
    }
    Last edited by ostamo2; 04-01-2012 at 06:06 PM.
    ME WANT AGENTS ME WANT AGENTS ME WANT AGENTS

  2. #2
    Join Date
    Aug 2005
    Location
    Washington for now..
    Posts
    25
    The only thing that catches my eye are the calls to sprintf. My compiler will not allow me to pass a string to sprintf, but I believe there may still be an issue with encoding. I remember having problems trying to set window titles and such. Here you can see what I got to work, it may or may not help you.

    Code:
    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char * argv[]) {
      std::basic_string<wchar_t> s = L"Hello world";
      wchar_t buffer[32];
    
      swprintf(buffer, 16, L"%ls", s.c_str());
    
      wprintf(L"%ls\n", buffer);
    
      return 0;
    }
    Note: when using sprintf and s.c_str() on a standard string, the %ls modifier output nothing. I think this format is probably right for what you are trying to do but I am not sure. I noticed you are not calling the .c_str() member function of your equipment, this makes my compiler complain so your sprintf may have special help. I hope this helps you get where you need to be, otherwise, do not mind me.
    Last edited by DrepMagnus; 04-02-2012 at 07:50 AM.

  3. #3
    Join Date
    Jun 2003
    Location
    Trier, Germany
    Posts
    1,350
    You're mixing C and C++ there, which is always asking for trouble.

    In particular, you cannot use fread/fwrite for serializing non-POD data like Equipment. What you really want to do is write Serialize()/Deserialize member functions that convert Equipment to/from a byte stream and only use fread/fwrite on that bytestream. Windows already provides some helpers for this task, like MFC's serialization library (which served as a major inspiration for Boost.Serialization).

    DrepMagnus is also completely right about swprintf on std::string: Using %s on a plain C++ string object will yield garbage results (which doesn't matter in this case, because the string was garbage in the first place). You will want to use c_str().

  4. #4
    Join Date
    Jun 2003
    Posts
    150
    Expounding a bit more on what Comic is saying, string in C++ is a wrapper around a C style string, which is just a character array. I believe it actually contains just a pointer to the dynamically allocated array that the value of the string is stored in, which could be anywhere on the heap. When you use fwrite() it is just sending whatever data is at the address of the string class, which contains a pointer to where the string values are at(among other thing), not the character values themselves. fwrite() just writes out the bytes as they are laid out in memory.

    With more complex data types(types that don't just use the base data types such as int, float, char, etc), you have to go through serialization as Comic said. Which is specific to the object itself.

  5. #5
    Join Date
    Aug 2004
    Location
    little rock arkansas
    Posts
    3,482
    thanks guys i will look more into it, maybe i will just use structs LOL i appreciate the help
    ME WANT AGENTS ME WANT AGENTS ME WANT AGENTS

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •