>这是一个值得信赖的应用程序(不适用于我的应用程序)
>在Application.Startup事件完成之前(对我的应用程序不适用)
>响应用户启动的操作,例如,在按钮Click事件处理程序中(这是我想要工作的)
在我试图让它工作的过程中,我把事情变得非常简单,并且直接在按钮点击事件处理程序后面的代码中调用方法,如下所示,但它没有任何效果.
void closeButton_Click(object sender,RoutedEventArgs e) { var mainWindow = Application.Current.MainWindow; mainWindow.Close(); }
当我附加调试器并设置“抛出异常时中断”时,我可以看到异常
SecurityException: Access to the property or method call is not
allowed unless the application has elevated permissions,or the code
was called through a user initiated action.
我已经尝试在XAML和代码隐藏中附加事件处理程序(不是在同一时间)
<Button x:Name="closeButton" Content="Close" Click="closeButton_Click" />
要么
closeButton.Click += closeButton_Click;
没有成功.我已经非常仔细地阅读了User-Initiated Events文档,并且无法理解为什么我的代码不被视为用户启动.我已经在调试和发布模式下以及没有成功附加调试器时尝试了这一点.如果我将“在浏览器外部运行时需要提升的信任”更改为true,则关闭调用将按预期工作.
我已经重新定义了我的应用程序要求来解决这个问题,但我真的很想了解我做错了什么;-)
更新:SonOfPirate的答案表明此方法的文档不准确,但我不相信.使用反射工具dotPeek抛出异常的方法是
private void CheckForPermissions() { if (!Application.Current.HasElevatedPermissions && !XcpImports.IsUserInitiatedAction() && Application.Current.ApplicationStarted) throw new SecurityException(Resx.GetString("Window_AccessNotAllowed")); }
我觉得这有点令人困惑,所以我已经嘲笑了代码并为它编写了单元测试,如gist所示,你可以从结果中看到我应该可以从一个不受信任的应用程序调用close,前提是它是用户启动.
安全异常消息
Access to the property or method call is not allowed unless the application has elevated permissions,or the code was called through a user initiated action.
解决方法
You can call this method only in the following cases:
- In response to a user-initiated action,for example,in a button Click event handler.
- Before the Application.Startup event has completed (that is,in an Iapplicationservice.StartService method,an IApplicationLifetimeAware.Starting
method,or a Startup event handler).- In a trusted application.
如您所见,您需要启用提升的信任.
UPDATE
我承认,微软使用的措辞有点误导,与前三种情况相结合的前两种情况都是如此.如果措辞更准确,也许会更清楚:
You can call this method only in a trusted application in either of the following cases:
- In response to a user-initiated action,an IApplicationLifetimeAware.Starting method,or a Startup event handler).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。