简单的资源管理器






2.92/5 (13投票s)
2003年6月6日

67613

786
这是一个简单的类,您可以使用它来加载和使用另一个资源 DLL,如果它在运行时存在。
引言
我创建了这个类是为了帮助我在运行时加载不同的资源 DLL(如果存在)。例如,一个多语言应用程序。如果存在另一个资源 DLL(其名称在编译时指定),它可以将其加载并用作应用程序的资源。
让我们看一下类的头文件。它非常简单,我认为注释很好地描述了各个方法。
class CResourceManager { // Operations public: // Constructor CResourceManager(); // Destructor virtual ~CResourceManager(); // Load external resource dll. If file not present or unable to load, // it returns FALSE. If it is present, it is loaded but does not affect // the default resource of the application. You should call this if you // want to manage the current application resource and an external one. BOOL Setup(CString); // Load external resource dll and set it as default for application. // Before setting as default, the current resource handle is stored // in case when you need to access the resource there. // If file not present or unable to load, the current application // resource is being used. BOOL SetupEx(CString); // Get string from string table of external resource if any // If there is an external resource loaded, GetString will retrieve from // there. If not, it will retrieve from the application default resource. CString GetString(UINT); // Attributes private: HINSTANCE m_hExternalResource; // Handle to external resource loaded HINSTANCE m_hApplicationResource; // Handle to current application resource };
使用代码
下面是一个如何使用类的方法的示例。首先,您需要创建一个 CResourceManager
对象。您可以将其放在全局或作为应用程序类的成员。然后,如以下所示,在 InitInstance(...)
中调用 Setup(...)
方法。
BOOL CtestApp::InitInstance() { // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. InitCommonControls(); CWinApp::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Load and set the specified resource dll as default if it is present. // Normally the location of the dll would be the same as the executable // and you would need to determine it with GetModuleFileName(...), but // in this case, i assume i know where the dll is located. m_oResourceManager.SetupEx(_T("C:\\MyProjects\\anotherres.dll")); . . . // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand return TRUE; }
至于清理加载的资源 DLL,析构函数将处理它,如下所示。
CResourceManager::~CResourceManager() { // Check if handle is valid, free library if (m_hExternalResource != NULL) FreeLibrary(m_hExternalResource); // Init handles m_hExternalResource = NULL; m_hApplicationResource = NULL; }
关注点
我承认这个类在处理其他资源问题方面有所不足,但如果您愿意,可以随意扩展它。:)