GetModuleFileName(2011-08-08 11:20:16)

本文详细解析了GetModuleFileName函数的使用方法、参数意义及返回值,并对比了其与.\的区别,提供了获取应用程序目录路径的两种方法,同时介绍了如何在MFC程序中获取自身路径,以及获取模块句柄的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
 
1.函数原型:
  DWORD GetModuleFileName(
  HMODULE hModule,
  LPTSTR lpFilename,
  DWORD nSize
  );
  函数参数说明:
  hModule HMODULE 装载一个程序实例的句柄。如果该参数为NULL,该函数返回该当前应用程序全路径。
  lpFileName LPTSTR 是你存放返回的名字的内存块的指针,是一个输出参数
  nSize DWORD ,装载到缓冲区lpFileName的最大值
  函数返回值:
  如果返回为成功,将在lpFileName的缓冲区当中返回相应模块的路径,如果所为的nSize过小,哪么返回仅按所设置缓冲区大小返回相应字符串内容。
  如果函数失败,返回值将为0,并返回GetLastError异常代码。
  需要的头文件为:

  include Windows.h

2.

.\\与API函数GetModuleFileName获取应用程序目录有何不一样?
采用.\\也能获得应用程序目录,采用GetModuleFileName也能获得,二者有何不同?
一样!
一个是相对路径,一个是绝对路径
.\\是的到应用程序的当前目录,但当前目录不一定等于应用程序执行文件的所在目录,一个应用程序被启动时,当前目录是可以被任意设置的。
GetModuleFileName()得到模块的完整路径名,例如,你载入c:\windows\system32\a.dll,得到模块句柄h,则你可以用GetModuleFileName()得到h模块的完整路径名。
.\\一般用在包含头文件的语句中。
另一个是程序编译后起作用的,例如,打开自定义的配置文件等。
如何去取得这个Hanlde?
如果你直接用LoadLibrary()或AfxLoadLibrary()载入dll,该函数返回值就是handle;
如果你隐式载入dll, 用GetModuleHandle("dll文件名")也可以得到handle;

MFC程序得到本身路径

在开发工程中,往往需要知道当前程序本身所在目录。
一种方法是在程序安装的时候利用安装程序把文件路径写入注册表。在较大的程序中,这种方法比较常用
另一种,就是在程序得到路径。这样,程序随便移动到哪里,都可以得到正确的路径。这也是本文介绍的方法。

方法一:
[code]
//得到帮助文件的路径
CString strFullName = AfxGetApp()->m_pszHelpFilePath;
//得到的是:X:\XXXX\XXX.hlp

//解析路径,得到当前运行程序所在目录
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];

_splitpath(strAppName, drive, dir, NULL,NULL);
CString strPath;
strPath.Format("%s%s", drive, dir);
//strPath即为得到的当前运行程序所在目录
[/code]
另外,AfxGetApp()->m_pszAppName 得到应用程序名称
AfxGetApp()->m_pszExeName 得到程序文件名,不包括扩展名

方法二:
得到全路径
TCHAR exeFullPath[MAX_PATH]; // MAX_PATH
GetModuleFileName(NULL,exeFullPath,MAX_PATH);//得到程序模块名称,全路径
也就是当前运行程序的全路径
利用方法一的解析路径的方法,即可得到程序所在路径。

GetModuleFileName函数原型
DWORD GetModuleFileName(
HMODULE hModule, // handle to module。将要得到的模块的句柄。如果是当前模块,NULL
LPTSTR lpFilename, // path buffer 得到的文件名。
DWORD nSize // size of buffer 一般MAX_PATH就可以了

//============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\NXopen\BaiduSyncdisk\studio\jiamiceshi\ui\jiamiceshi.cpp // // This file was generated by the NX Block UI Styler // Created by: MICH-ROG // Version: NX 12 // Date: 08-19-2025 (Format: mm-dd-yyyy) // Time: 14:36 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C++ source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ //These includes are needed for the following template code //------------------------------------------------------------------------------ #include "jiamiceshi.hpp" // 配置文件读取工具类 class ConfigReader { public: // 获取整数配置值 static int GetInt(const char* section, const char* key, int defaultValue) { char configPath[MAX_PATH] = { 0 }; // 获取当前DLL路径 HMODULE hModule = GetModuleHandle(NULL); if (hModule) { GetModuleFileName(hModule, configPath, MAX_PATH); } // 替换文件名为config.ini char* lastBackslash = strrchr(configPath, '\\'); if (lastBackslash) { strcpy_s(lastBackslash + 1, MAX_PATH - (lastBackslash - configPath) - 1, "config.ini"); } else { strcat_s(configPath, MAX_PATH, "\\config.ini"); } // 使用Windows API读取INI文件中的整数值 return GetPrivateProfileInt(section, key, defaultValue, configPath); } }; // 添加日期限制检查函数实现 bool jiamiceshi::CheckDateLimit() { // 从配置文件读取日期,如果没有则使用默认值 const int limitYear = ConfigReader::GetInt("Expiry", "Year", 2025); const int limitMonth = ConfigReader::GetInt("Expiry", "Month", 7); const int limitDay = ConfigReader::GetInt("Expiry", "Day", 30); // 获取当前系统时间 time_t now = time(0); tm* ltm = localtime(&now); int currentYear = 1900 + ltm->tm_year; int currentMonth = ltm->tm_mon + 1; int currentDay = ltm->tm_mday; // 比较日期 if (currentYear > limitYear) { return true; } else if (currentYear == limitYear) { if (currentMonth > limitMonth) { return true; } else if (currentMonth == limitMonth) { if (currentDay > limitDay) { return true; } } } return false; } // 未过期,功能可用 using namespace NXOpen; using namespace NXOpen::BlockStyler; //------------------------------------------------------------------------------ // Initialize static variables //------------------------------------------------------------------------------ Session *(jiamiceshi::theSession) = NULL; UI *(jiamiceshi::theUI) = NULL; //------------------------------------------------------------------------------ // Constructor for NX Styler class //------------------------------------------------------------------------------ jiamiceshi::jiamiceshi() { try { // Initialize the NX Open C++ API environment jiamiceshi::theSession = NXOpen::Session::GetSession(); jiamiceshi::theUI = UI::GetUI(); theDlxFileName = "jiamiceshi.dlx"; theDialog = jiamiceshi::theUI->CreateDialog(theDlxFileName); // Registration of callback functions theDialog->AddApplyHandler(make_callback(this, &jiamiceshi::apply_cb)); theDialog->AddOkHandler(make_callback(this, &jiamiceshi::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &jiamiceshi::update_cb)); theDialog->AddInitializeHandler(make_callback(this, &jiamiceshi::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &jiamiceshi::dialogShown_cb)); } catch(exception& ex) { //---- Enter your exception handling code here ----- throw; } } //------------------------------------------------------------------------------ // Destructor for NX Styler class //------------------------------------------------------------------------------ jiamiceshi::~jiamiceshi() { if (theDialog != NULL) { delete theDialog; theDialog = NULL; } } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ extern "C" DllExport void ufusr(char *param, int *retcod, int param_len) { jiamiceshi *thejiamiceshi = NULL; try { thejiamiceshi = new jiamiceshi(); // The following method shows the dialog immediately thejiamiceshi->Show(); } catch(exception& ex) { //---- Enter your exception handling code here ----- jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } if(thejiamiceshi != NULL) { delete thejiamiceshi; thejiamiceshi = NULL; } } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ extern "C" DllExport int ufusr_ask_unload() { //return (int)Session::LibraryUnloadOptionExplicitly; return (int)Session::LibraryUnloadOptionImmediately; //return (int)Session::LibraryUnloadOptionAtTermination; } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ extern "C" DllExport void ufusr_cleanup(void) { try { //---- Enter your callback code here ----- } catch(exception& ex) { //---- Enter your exception handling code here ----- jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } int jiamiceshi::Show() { try { theDialog->Show(); } catch(exception& ex) { //---- Enter your exception handling code here ----- jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ void jiamiceshi::initialize_cb() { try { group0 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group0")); selection0 = dynamic_cast<NXOpen::BlockStyler::SelectObject*>(theDialog->TopBlock()->FindBlock("selection0")); expression0 = dynamic_cast<NXOpen::BlockStyler::ExpressionBlock*>(theDialog->TopBlock()->FindBlock("expression0")); } catch(exception& ex) { //---- Enter your exception handling code here ----- jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any value set //here will take precedence and dialog will be launched showing that value. //------------------------------------------------------------------------------ // 修改对话框显示回调函数 void jiamiceshi::dialogShown_cb() { try { // 在对话框显示时检查日期限制 if (CheckDateLimit()) { // 显示过期消息 theUI->NXMessageBox()->Show("MICH-明:V:jianjian19951231", NXMessageBox::DialogTypeError, "此功能已过期,无法使用!\n请联系开发者获取更新版本。"); // 禁用所有控件 group0->SetEnable(false); // 禁用组 selection0->SetEnable(false); // 禁用选择对象控件 expression0->SetEnable(false); // 禁用表达式控件 // 隐藏确定和应用按钮 PropertyList* okProps = GetBlockProperties("OK"); // 获取OK按钮属性 if (okProps) { okProps->SetLogical("Show", false); // 隐藏确定按钮 } PropertyList* applyProps = GetBlockProperties("Apply"); // 获取应用按钮属性 if (applyProps) { applyProps->SetLogical("Show", false); // 隐藏应用按钮 } } } catch (exception& ex) { // 异常处理 theUI->NXMessageBox()->Show("错误提示:", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ // 修改应用回调函数 int jiamiceshi::apply_cb() { int errorCode = 0; try { // 检查日期限制 if (CheckDateLimit()) { theUI->NXMessageBox()->Show("MICH-明:V:jianjian19951231", NXMessageBox::DialogTypeError, "此功能已过期,无法执行操作!"); return 1; // 返回错误代码 }//结束日期检查 //---- Enter your callback code here ----- } catch(exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ int jiamiceshi::update_cb(NXOpen::BlockStyler::UIBlock* block) { try { if(block == selection0) { //---------Enter your code here----------- } else if(block == expression0) { //---------Enter your code here----------- } } catch(exception& ex) { //---- Enter your exception handling code here ----- jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ int jiamiceshi::ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); } catch(exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; jiamiceshi::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Description: Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ PropertyList* jiamiceshi::GetBlockProperties(const char *blockID) { return theDialog->GetBlockProperties(blockID); } 报错:严重性 代码 说明 项目 文件 行 禁止显示状态 错误 C2039 "CreateDialogParamA": 不是 "NXOpen::UI" 的成员 jiamiceshi D:\NXopen\BaiduSyncdisk\studio\jiamiceshi\jiamiceshi.cpp 123 错误(活动) E0135 class "NXOpen::UI" 没有成员 "CreateDialogParamA" jiamiceshi D:\NXopen\BaiduSyncdisk\studio\jiamiceshi\jiamiceshi.cpp 120 错误 C2059 语法错误:“,” jiamiceshi D:\NXopen\BaiduSyncdisk\studio\jiamiceshi\jiamiceshi.cpp 123
最新发布
08-20
帮我优化代码, //------------------------------------------------------------------------------ //These includes are needed for the following template code //------------------------------------------------------------------------------ #include "HoistingHole.hpp" using namespace NXOpen; using namespace NXOpen::BlockStyler; //------------------------------------------------------------------------------ // Initialize static variables //------------------------------------------------------------------------------ Session *(HoistingHole::theSession) = NULL; UI *(HoistingHole::theUI) = NULL; //------------------------------------------------------------------------------ // Constructor for NX Styler class //------------------------------------------------------------------------------ HoistingHole::HoistingHole() { try { WCHAR temp[256]; GetModuleFileName(_AtlBaseModule.GetModuleInstance(), temp, 256); wstring ws(temp); string strDllPath(ws.begin(), ws.end()); // DLL 运行路径 string dllPath = strDllPath.substr(0, strDllPath.find_last_of("\\") + 1); // Initialize the NX Open C++ API environment HoistingHole::theSession = NXOpen::Session::GetSession(); HoistingHole::theUI = UI::GetUI(); theDlxFileName = "HoistingHole.dlx"; theDialog = HoistingHole::theUI->CreateDialog(dllPath + theDlxFileName); // Registration of callback functions theDialog->AddApplyHandler(make_callback(this, &HoistingHole::apply_cb)); theDialog->AddOkHandler(make_callback(this, &HoistingHole::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &HoistingHole::update_cb)); theDialog->AddFilterHandler(make_callback(this, &HoistingHole::filter_cb)); theDialog->AddInitializeHandler(make_callback(this, &HoistingHole::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &HoistingHole::dialogShown_cb)); } catch(exception& ex) {
03-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值