Win32从选项卡式界面保存文本文件

时间:2013-10-25 19:21:45

标签: winapi save controls edit tabbed

我正在使用MS visual c ++ 2010 express来编写记事本程序。我需要能够从我的选项卡界面保存文件(每个编辑控件都存储在一个向量中)。我似乎无法弄清楚如何保存,具体取决于用户可以看到哪个编辑控件(活动选项卡)。到目前为止我尝试过的所有内容都不会保存内容或只保存第一个编辑控件。当用户将新文件添加到选项卡式界面时,它会将该编辑控件添加到向量的后面。这是我最近的尝试:

    std::vector<HWND>vect;

    BOOL SaveTextFileFromEdit( HWND hEdit, LPCTSTR pszFileName )
    {
      HANDLE hFile;
      BOOL bSuccess = FALSE;

      hFile = CreateFile( pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );

      if( hFile != INVALID_HANDLE_VALUE )
      {
        DWORD dwTextLength = GetWindowTextLength( hEdit );

        if( dwTextLegth > 0 )
        {
          DWORD dwBufferSize = dwTextLength + 1;
          LPSTR pszText = ( LPSTR )GlobalAlloc( GPTR, dwBufferSize );

          if( pszText != NULL )
          {
            if( GetWindowText( hEdit, pszText, dwBufferSize ) )
            {
              DWORD dwWritten;

              if( WriteFile( hFile, pszText, dwTextLength, &dwWritten, NULL ) )
                bSuccess = TRUE;
            }
            GlobalFree( pszText );
          }
        }
        CloseHandle( hFile );
      }
      return bSuccess;
    }

    LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
    {
      case WM_COMMAND:
        switch( LOWORD( wParam ) )
        {
          case ID_FILE_SAVEAS:
            {
              OPENFILENAME ofn;
              char szFileName[ MAX_PATH ] = "";
              ZeroMemory( &ofn, sizeof( ofn ) );

              ofn.lStructSize = sizeof( ofn );
              ofn.hwndOwner   = hwnd;
              ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
              ofn.lpstrFile   = szFileName;
              ofn.nMaxFile    = MAX_PATH;
              ofn.lpstrDefExt = "txt";
              ofn.flags       = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;

              if( GetSaveFileName( &ofn ) )
              {
                HWND hEdit, hTabs;
                hTabs = GetDlgItem( hwnd, IDC_MAIN_TAB );
                int curTab = TabCtrl_GetCurSel( hTabs );

                hEdit = GetDlgItem( hTabs, IDC_MAIN_EDIT );
                // This is what i did have: hEdit = GetDlgItem( vect[ curTab ], IDC_MAIN_EDIT );
                // Which wasn't saving anything
                if( SaveTextFileFromEdit( hEdit, szFileName ) )
                {
                  // EVERYTHING IS GOOD
                }
              }
            }
            break;
        }
        break;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

如果向量具有每个编辑控件的HWND,则根本不需要GetDlgItem:您已经拥有它将返回的HWND。

hEdit = vect[ curTab ];