OpenFileDialog 类在 c++ 中无法正常工作
OpenFileDialog class not working properly in c++
我想显示由OpenFileDialog打开的文件名,但它将错误的文本发送到标题栏中。我更改了项目的字符集,但没有帮助。这是我的代码:
打开文件对话框 .h :
class OpenFileDialog
{
public:
OpenFileDialog(){};
void CreateOpenFileDialog(HWND hWnd, LPCWSTR Title, LPCWSTR InitialDirectory, LPCWSTR Filter, int FilterIndex);
~OpenFileDialog(){};
LPCWSTR result=L"";
};
打开文件对话框 .cpp :
void OpenFileDialog::CreateOpenFileDialog(HWND hWnd, LPCWSTR Title, LPCWSTR InitialDirectory, LPCWSTR Filter, int FilterIndex)
{
OPENFILENAME ofn;
TCHAR szFile[MAX_PATH];
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = ' ';
ofn.hwndOwner = hWnd;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = Filter;
ofn.nFilterIndex = FilterIndex;
ofn.lpstrTitle = Title;
ofn.lpstrInitialDir = InitialDirectory;
ofn.lpstrFileTitle = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn))
{
result = ofn.lpstrFile;
}
else
{
result = L"Empty";
}
}
并在 Windows 程序中WM_COMMAND:
case WM_COMMAND:
{
if (LOWORD(wParam) == ID_FILE_OPEN)
{
OpenFileDialog ofd;
ofd.CreateOpenFileDialog(hwnd, L"Test", L"C:\", L"All files(*.*) *.* TextFiles(*.txt) *.txt ", 2);
SetWindowText(hwnd, ofd.result);
}
break;
}
多谢。
在你的函数CreateOpenFileDialog()
中,用于存储文件名的缓冲区是一个本地数组szFile[MAX_PATH]
。 初始化ofn
结构中的lpstrFile = szFile
,确保GetOpenFileName()
将用户输入的结果放在正确的位置。
问题是,一旦你从 CreateOpenFileDialog()
返回,它的局部变量就会被销毁,包括包含文件名的缓冲区。因此,您使用 result = ofn.lpstrFile;
设置的result
指针随后指向无效的内存位置。
可以通过在 OpenFileDialog
构造函数中直接在 result
中分配缓冲区(或使其成为数组)并直接将此指针与 ofn.lpstrFile = buffer;
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- C++程序已停止工作-求解常微分方程