如何使用资源进行Windows API自定义对话框模板?

时间:2014-01-15 16:05:48

标签: c++ controltemplate getopenfilename

我正在尝试在C ++中的OPENFILENAME结构上使用自定义模板,并且无法弄清楚我到底做错了什么。以下是我到目前为止的情况:

#include <windows.h>
#include <iostream>
#include "resource.h"

void main() {
    HWND hwnd = NULL;// owner window

    OPENFILENAME ofn;
    CHAR File[256];
    ZeroMemory(&ofn, sizeof(OPENFILENAME));

    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = hwnd;
    ofn.hInstance = NULL; 
    ofn.lpstrCustomFilter = NULL;
    ofn.nMaxCustFilter = 0;
    ofn.nFilterIndex = 0;
    ofn.lpstrFile = File;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof(File);
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = MAX_PATH;
    ofn.lpstrInitialDir = NULL;
    ofn.lpstrTitle = NULL;
    ofn.Flags = OFN_ENABLETEMPLATE;
    ofn.nFileOffset = 0;
    ofn.nFileExtension = 0;
    ofn.lpstrDefExt = NULL;
    ofn.lCustData = 0L;
    ofn.lpfnHook = NULL;
    ofn.lpTemplateName = "IDD_DIALOGBAR";


    if (GetOpenFileName(&ofn)==TRUE) 
    {
        //do something with filename
    }

    std::cout << CommDlgExtendedError();
}

IDD_DIALOGBAR是我添加到项目中的自定义资源。我这样做是通过在Visual Studio中创建一个新的空C ++项目,然后在解决方案资源管理器中右键单击项目名称,然后单击“添加” - >“资源”。然后,我从可用的资源列表中选择了“IDD_DIALOGBAR”。这为项目添加了一个新资源,当我在Visual Studio中切换到“资源视图”时可以查看该资源。

运行程序时,对话框根本不显示。 CommDlgExtendedError()的结果是CDERR_FINDRESFAILURE: The common dialog box function failed to find a specified resource

我也尝试过更改

ofn.lpTemplateName = "IDD_DIALOGBAR"

ofn.lpTemplateName = MAKEINTRESOURCE(IDD_DIALOGBAR)

但是这导致了不同的错误消息:

CDERR_DIALOGFAILURE: The dialog box could not be created. The common dialog box function's call to the DialogBox function failed. For example, this error occurs if the common dialog box call specifies an invalid window handle.

我错过了什么?我没有正确引用资源吗?

1 个答案:

答案 0 :(得分:0)

需要将

ofn.hInstance设置为具有对话框模板资源的模块(可执行文件或DLL)的HINSTANCE

相关问题