windows 获取运行可执行文件的文件句柄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4750897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:01:58  来源:igfitidea点击:

Get file handle to running executable

c++cwindowswinapi

提问by Sparafusile

I am trying to call GetFileInformationByHandle on the executable of my own running program. This means I'll need to get a file handle to the .exe that started my program. Is there any way to do this?

我试图在我自己正在运行的程序的可执行文件上调用 GetFileInformationByHandle。这意味着我需要获取启动程序的 .exe 的文件句柄。有没有办法做到这一点?

Failing that, is there any way to get the nFileIndexHigh and nFileIndexLow for a running executable?

如果做不到这一点,有没有办法为正在运行的可执行文件获取 nFileIndexHigh 和 nFileIndexLow?

回答by James

DWORD WINAPI GetModuleFileNameEx(   
   __in      HANDLE hProcess,
   __in_opt  HMODULE hModule,
   __out     LPTSTR lpFilename,
   __in      DWORD nSize ); 

Second parameter should be NULL and you will get the name of the current executable.

第二个参数应为 NULL,您将获得当前可执行文件的名称。

EDIT:

编辑:

Then open the file.

然后打开文件。

回答by Economou Kyriakos

Here it is a way to do this. I hope this helps:

这是一种方法来做到这一点。我希望这有帮助:

#include <Windows.h>
#include <iostream>
using namespace std;

//declare a BY_HANDLE_FILE_INFORMATION structure
BY_HANDLE_FILE_INFORMATION fileinfo;

int main()
{
    // clear everything in the structure, this is optional
    ZeroMemory(&fileinfo, sizeof(BY_HANDLE_FILE_INFORMATION));

    // obtain a handle to the file, in this case the file
    // must be in the same directory as your application
    HANDLE myfile = NULL;
    myfile = CreateFileA("example.exe",0x00,0x00,NULL,
                         OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

    // if we managed to obtain the desired handle
    if(myfile!=INVALID_HANDLE_VALUE)
    {
        //try to fill the structure with info regarding the file
        if(GetFileInformationByHandle(myfile, &fileinfo))
        {
            // Ex: show the serial number of the volume the file belongs to
            cout << endl << hex << fileinfo.dwVolumeSerialNumber << endl;
        }
        // you should close the handle once finished
        CloseHandle(myfile);
    }
    system("pause");
    return 0;
}

回答by Andrey

You should try GetCommandLineto get path to executable. Then open and here is your handle.

您应该尝试GetCommandLine来获取可执行文件的路径。然后打开,这是你的把手。

回答by Puppy

GetModuleHandle is the solution here.

GetModuleHandle 是这里的解决方案。

http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx

If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).

如果此参数为 NULL,则 GetModuleHandle 返回用于创建调用进程的文件(.exe 文件)的句柄。