VB and VBA Users Source Code: Determining the name of the process/application which created your DLL
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Determining the name of the process/application which created your DLL
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, July 11, 2002
Hits:
800
Category:
Windows API
Article:
When authoring a DLL/OCX it is sometimes useful to be able to determine the name of your owner (the application that created you). The following code returns the full path and file name of the application which owns a specified process: Option Explicit Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long Private Declare Function CloseHandle Lib "Kernel32.dll" (ByVal Handle As Long) As Long Private Declare Function OpenProcess Lib "Kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long Private Declare Function GetModuleFileNameExA Lib "PSAPI.DLL" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long Private Declare Function EnumProcessModules Lib "PSAPI.DLL" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long 'Purpose : Allows DLLs/OCXs to determine the name of the process which owns them. 'Inputs : [lPID] The process ID to find the name of (defaults to current process). 'Outputs : Returns the filename which owns the specified process. 'Author : Andrew Baker 'Date : 28/04/2001 'Notes : Useful in DLLs which are require different behaviour depending on the ' process which owns them. eg. behave differently when loaded by Excel. ' eg. in DLL use: ' Dim sOwnerApplication As String ' sOwnerApplication = ProcessParentFileName Function ProcessParentFileName(Optional lPID As Long) As String Dim lHwdProcess As Long Dim alHwdModules(1 To 200) As Long Dim lSize As Long, lReturn As Long Const clSize As Long = 500 Const PROCESS_QUERY_INFORMATION = 1024, PROCESS_VM_READ = 16, MAX_PATH = 260 Dim sModuleName As String * MAX_PATH If lPID = 0 Then 'Get the current process ID lPID = GetCurrentProcessId End If 'Open the process lHwdProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, lPID) If lHwdProcess <> 0 Then 'Get an array of module handles for this process lReturn = EnumProcessModules(lHwdProcess, alHwdModules(1), 200, lSize) If lReturn <> 0 Then 'Received Module Array, get the ModuleFileName 'Get Process Name lReturn = GetModuleFileNameExA(lHwdProcess, alHwdModules(1), sModuleName, clSize) 'Remove trailing spaces ProcessParentFileName = Left$(sModuleName, lReturn) End If End If 'Close the handle to this process lReturn = CloseHandle(lHwdProcess) End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder