最近整理了一些获取当前模块路径的代码,都是通过调用 GetModuleFileName() 来获取
- DWORD WINAPI GetModuleFileName(
- _In_opt_ HMODULE hModule,
- _Out_ LPTSTR lpFilename,
- _In_ DWORD nSize
- );
- hModule
-
[in] Handle to the module whose executable file name is being requested.
If this parameter is NULL, GetModuleFileName returns the path for the file used to create the calling process.
- lpFilename
-
[out] Pointer to a buffer that is filled in with the path and file name of the module.
- nSize
-
[in] Specifies the length, in characters, of the lpFilename buffer.
If the length of the path and file name exceeds this limit, the string is truncated.
第一种:
- char szBuff[MAX_PATH] = {0};
- HMODULE hModuleInstance = _AtlBaseModule.GetModuleInstance();
- GetModuleFileNameA(hModuleInstance,szBuff, MAX_PATH);
- CString strTmp = CA2T(szBuff);
- m_strExePath = strTmp.Mid(0, strTmp.ReverseFind('\\'));
适用于获取dll、exe路径,可在console、MFC、ATL工程中使用。
第二种:
- <pre name="code" class="cpp"> char szBuff[MAX_PATH] = {0};
GetModuleFileName(AfxGetStaticModuleState()->m_hCurrentInstanceHandle,szBuff,MAX_PATH);
适用于获取dll、exe路径,可在MFC、ATL工程中使用,不能再console中使用。
第三种:
- <span style="white-space:pre"> </span>GetModuleFileName((HMODULE)&__ImageBase, szFull, _MAX_PATH);
适用于获取dll、exe路径,可在MFC、ATL工程中使用,不能再console中使用。
最后插一句CString的GetBuffer():