首先,我是一个幼稚的开发者,并没有深入理解这些代码。
我在尝试获取应用程序版本号的代码块中遇到了访问被拒绝的问题。
场景:在 Visual Studio 中运行代码时没有问题。但是当安装文件在不同的机器上运行并检查日志时,它会抛出“Win32Exception”: 访问被拒绝。
(程序在安装后自动运行。实际上,在安装此应用程序之前,已经安装了一个“看门狗服务”,该服务会自动运行应用程序并在关闭后恢复它。因此,我认为我无法将requestedExecutionLevel设置为requireAdmin,这可能会显示确认对话框并允许用户控制运行应用程序。)
我需要解决这个问题。阅读了一些博客之后,我认为这可能是由于缺少足够的权限来检索所需信息。但我仍然不清楚如何解决这个问题。
日志文件中的异常:
场景:在 Visual Studio 中运行代码时没有问题。但是当安装文件在不同的机器上运行并检查日志时,它会抛出“Win32Exception”: 访问被拒绝。
(程序在安装后自动运行。实际上,在安装此应用程序之前,已经安装了一个“看门狗服务”,该服务会自动运行应用程序并在关闭后恢复它。因此,我认为我无法将requestedExecutionLevel设置为requireAdmin,这可能会显示确认对话框并允许用户控制运行应用程序。)
我需要解决这个问题。阅读了一些博客之后,我认为这可能是由于缺少足够的权限来检索所需信息。但我仍然不清楚如何解决这个问题。
日志文件中的异常:
[ 1,11216] 2017-04-17T11:43:53 - -------------------- Win32Exception caught --------------------
[ 1,11216] 2017-04-17T11:43:53 - Access is denied
[ 1,11216] 2017-04-17T11:43:53 - (Win32Err=0x00000005)
[ 1,11216] 2017-04-17T11:43:53 - Stack trace is :
[ 1,11216] 2017-04-17T11:43:53 - at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
at System.Diagnostics.Process.get_MainModule()
at IMPMDesktopClient.BaseIMClientDriver.GetVersion(UIntPtr windowUIntPtr)
at IMPMDesktopClient.WindowDetector.Hooks.WindowsEventArgs..ctor(Int32 eventNum, UIntPtr windowHandle, Int32 idObject, Int32 idChild, String clsName, Rectangle pos)
at IMPMDesktopClient.WindowDetector.Hooks.EventHooks.CheckForWindowOfInterest(UIntPtr hWnd, UIntPtr arg)
at IMPMDesktopClient.WindowDetector.Hooks.EventHooks.CheckTopWindow(UIntPtr hWnd, UIntPtr arg)
at IMPMDesktopClient.Win32Interop.EnumWindows(WndEnumCallback callback, UIntPtr param)
at IMPMDesktopClient.WindowDetector.Hooks.EventHooks.DetectTheseWindowsNow(List`1 classes)
at IMPMDesktopClient.WindowDetector.WindowClassManager.OnPostRegistration()
[ 1,11216] 2017-04-17T11:43:53 - --------------------Win32Exception--------------------
获取版本信息的代码:
public static Version GetVersion(UIntPtr windowUIntPtr)
{
var noOfTrials = 2;
var threadSleepPeriod = 1000;
Process imProc = null;
while (noOfTrials > 0)
{
try
{
imProc = Win32Interop.GetWindowProcess(windowUIntPtr);
Version version;
try
{
version = GetModuleVersion(imProc.MainModule);
}
catch (System.ComponentModel.Win32Exception)
{
version = GetModuleVersion(imProc.Id);
}
// If getting version fails, retry it.
if (version == null || (version.Major == 0 && version.Minor == 0))
{
// The thread will sleep for 1s after 1st trial, 3s after 2nd trial.
Thread.Sleep(threadSleepPeriod);
noOfTrials--;
threadSleepPeriod += 2000;
}
else
return version;
if (noOfTrials == 0)
{
Log.Write(...);
}
}
catch (Exception ex)
{
Log.Write(...);
}
}
return new Version();
}