【问题标题】:How to programmatically change Windows update option?如何以编程方式更改 Windows 更新选项?
【发布时间】:2013-05-01 11:43:02
【问题描述】:

我目前正试图弄清楚,如何在 Windows 8 上将 Windows 更新设置为“让我选择是否安装”而不是“自动安装更新”。

根据Check from .NET if Windows Update is enabled我试过了:

WUApiLib.AutomaticUpdatesClass auc = new WUApiLib.AutomaticUpdatesClass();
// Doing some stuff

但出现以下错误:
Interop type 'WUApiLib.AutomaticUpdatesClass' cannot be embedded. Use the applicable interface instead.

The type 'WUApiLib.AutomaticUpdatesClass' has no constructors defined

按照Change windows updates setting with Powershell 中的答案,我做到了:

string subKey = @"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKey, true))
    key.SetValue("AUoptions", 4);

但是注册表中不存在子键导致Reference not set to an instance of an object错误。

Google 的其余结果都描述了如何手动更改此设置,这不是我想要的。

如何以编程方式将 Windows 更新设置为“让我选择是否安装”?

【问题讨论】:

  • 为了摆脱互操作错误,在 Visual Studio 中右键单击引用并转到它的属性,然后将“嵌入互操作类型”设置为 false。
  • @Arran 我明白了,现在第一个选项至少有效。很高兴知道,谢谢!现在我终于可以继续工作了:D

标签: c# windows windows-8 windows-update


【解决方案1】:

感谢Arran,让我朝着正确的方向迈出了一步:

要消除互操作错误,请在 Visual Studio 中右键单击引用并转到它的属性,然后将“嵌入互操作类型”设置为 false。

现在我不再遇到互操作错误,我设法得出结论;这是代码:

// using WUApiLib;
AutomaticUpdatesClass auc = new AutomaticUpdatesClass();
auc.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotifyBeforeInstallation;
auc.Settings.Save();

【讨论】:

  • 太棒了。对我有很大帮助。对于投反对票的人,你为什么要这么做?它可能对你完全没有价值,但其他人(比如我)发现它很有帮助。
【解决方案2】:

您可以通过将“嵌入互操作类型”保留为真,并从代码中省略 Class 后缀来避免“互操作类型 ... 无法嵌入”错误。

使用new AutomaticUpdates() 而不是new AutomaticUpdatesClass()

请参阅this answer 以获得关于省略类后缀的更好描述。他们说 .Net 4.0,但它在 4.5.1 中也适用于我。

例如:

// using WUApiLib;
AutomaticUpdates auc = new AutomaticUpdates();
auc.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotifyBeforeInstallation;
if (!auc.Settings.ReadOnly)
    auc.Settings.Save();

我注意到,当我将“嵌入互操作类型”切换为 false 时,它​​也将“复制本地”切换为 true。使用与上述类似的代码(并且 Embed = true),我能够在 Win7、8 和 10 上查询 NotificationLevel,而无需在我的应用程序旁边部署任何版本的“wuapilib.dll”。

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 2014-11-24
    • 1970-01-01
    • 2017-03-24
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2011-10-31
    相关资源
    最近更新 更多