0

我创建了一个带有一个编辑框和两个按钮的对话框。保存和加载按钮。

单击保存时,我想将编辑框中的文本保存到 txt 文件中,然后加载,将 txt 文件加载到编辑框中。现在保存/加载按钮似乎不起作用。保存按钮似乎创建了一个名为“u”的文件,而不是保存到选定的文件,并且加载按钮在选择文件后不执行任何操作。这是我到目前为止所拥有的:

#include <Windows.h>
#include <commdlg.h>
#include <fstream>
#include <string>
#include "resource.h"
using namespace std;

// Globals
HWND ghMainWnd = 0;
OPENFILENAME ofn;


// Handles
static HWND hEditBox    = 0;
static HWND hSaveButton = 0;
static HWND hLoadButton = 0;

// Contains file.
char szFile[100];

void save()
{

    char text[260];

    GetWindowText( hEditBox, text, 260 );

    ofstream saveFile( szFile, ios_base::binary );

    int length = strlen( text );
    saveFile.write( (char*)&length, sizeof(length) );
    saveFile.write( text, length );

}

void load()
{

    char text[260];

    ifstream loadFile( szFile, ios_base::binary );

    int length = 0;
    loadFile.read((char*)&length, sizeof(length));

    loadFile.read( text, length );

    text[length] = '\0';

    SetWindowText( hEditBox, text );
}

BOOL CALLBACK
WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{

    ZeroMemory( &ofn , sizeof( ofn ) );

    ofn.lStructSize     = sizeof( ofn );
    ofn.hwndOwner       = hWnd;
    ofn.lpstrFile       = szFile;
    ofn.lpstrFile[0]    = '\0';
    ofn.nMaxFile        = sizeof( szFile );
    ofn.lpstrFilter     = "All\0*.*\0Text\0*.TXT\0";
    ofn.nFilterIndex    = 1;
    ofn.lpstrFileTitle  = "Open/Save File Dialog";
    ofn.nMaxFileTitle   = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags           = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

    switch( msg )
    {
    case WM_INITDIALOG:
        hEditBox    = GetDlgItem( ghMainWnd, IDC_EDIT );
        hSaveButton = GetDlgItem( ghMainWnd, ID_SAVE );
        hLoadButton = GetDlgItem( ghMainWnd, ID_OPEN );
    return true;

    case WM_COMMAND:
        switch( LOWORD( wParam ) )
        {
        case ID_SAVE:
            GetSaveFileName( &ofn );
            save();
        return true;

        case ID_OPEN:
            GetOpenFileName( &ofn );
            load();
        return true;
        }
    return true;

    case WM_CLOSE:
        DestroyWindow( hWnd );
    return true;

    case WM_DESTROY:
        PostQuitMessage( 0 );
    return true;
    }

    return false;
}

INT WINAPI
WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR cmdLine, int showCmd )
{

    ghMainWnd = CreateDialog( hInstance, MAKEINTRESOURCE( IDD_TXTDLG ), 0, WndProc );
    ShowWindow( ghMainWnd, showCmd );

    MSG msg;
    ZeroMemory( &msg, sizeof( MSG ) );

    while( GetMessage( &msg, 0, 0, 0 ) )
    {
        if( ghMainWnd == 0 || !IsDialogMessage( ghMainWnd, &msg ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }

    return (int)msg.wParam;
}
4

1 回答 1

0

查看正在发生的事情的最佳方法是在调用之前显示文件的名称。您可以在调试器中执行此操作并查看它是什么,看看它是否错误。它将帮助您了解问题是否与函数调用或读取名称有关。我不记得 char 可以与 GetWindowText 一起使用(也许在非 Unicode 中可以)。

您还需要添加处理以检查字符串是否为空,以防万一。甚至可以验证名称是否有效。

于 2012-11-29T23:20:10.440 回答