进程加载DLL,或者加载OCX控件等模块。在开发这些模块的时候不可避免要使用一些外部的配置文件,最简单的方式就是存放在固定的一个路径下面,但是这样对于安装配置的时候就不是很友好,所以往往把这些配置文件和.dll放在一起,然后由dll/ocx它们告诉进程它们所在的路径,然后进程就到该路径下去读取配置文件。这里的实现借助的就是GetModuleFileName这个函数。

WINAPI DWORD GetModuleFileName(
  HMODULE hModule,
  LPWSTR lpFilename,
  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.

	//获取模块所在路径
	CString getModulePath() {
		TCHAR moduleName[MAX_PATH] = { 0 };
		GetModuleFileName(AfxGetInstanceHandle(), moduleName, MAX_PATH);
		TCHAR _strLongPath[MAX_PATH] = _T("\0");
		::GetLongPathName(moduleName, _strLongPath, MAX_PATH);
		CString strPath(_strLongPath);
		strPath = strPath.Left(strPath.ReverseFind(_T('\\')) + 1);
		return strPath;
	}

上述的代码实现在模块中,就可以获取模块自己所在的路径了。

需求源于开发一个给浏览器使用的OCX控件,控件的作用是控制摄像头进行图像相关处理,OCX中有些初始的参数想要写在.ini文件中。OCX控件一般安装后放在system32文件下或者program files目录下,然后.ini文件放在OCX同级的目录才是比较靠谱的,同时浏览器exe基本上和OCX不是在同一个目录的。