如何以编程方式更改Windows更新选项?

时间:2013-05-01 11:43:02

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

我目前正在试图找出,如何在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更新设置为“让我选择是否安装”?

2 个答案:

答案 0 :(得分:3)

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

  

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

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

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

答案 1 :(得分:0)

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

使用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();

我注意到当我将“Embed Interop Types”切换为false时,它也将“Copy Local”切换为true。使用类似于上面的代码(和Embed = true),我能够在Win7,8和10上查询NotificationLevel,而无需在我的应用程序旁边部署任何版本的“wuapilib.dll”。

相关问题