我可以使用C#/ .NET以编程方式禁用窗口自动播放function吗?

有谁知道一种方法来停用Windows的自动播放function使用C#/。NET?

一个小小的总结,为所有其他人寻找一个很好的方法来禁用/禁止自动播放。 到目前为止,我已经找到3种方法来以编程方式禁用自动播放:

  1. 拦截QueryCancelAutoPlay消息
  2. 使用注册表
  3. 实现COM接口IQueryCancelAutoPlay

最后,我选择了第三种方法,并使用IQueryCancelAutoPlay接口,因为其他方面有一些显着的缺点:

  • 第一种方法(QueryCancelAutoPlay)只能在应用程序窗口处于前台时禁止自动播放, 只导致前台窗口收到消息
  • 即使应用程序窗口位于后台,也可以在注册表中配置自动播放。 缺点:它需要重新启动当前运行的explorer.exe才能生效…所以这是暂时禁用自动播放的解决方案。

示例的实现

1. QueryCancelAutoPlay

  • 以编程方式抑制AutoRun (MSDN文章)
  • CodeProject:防止CD自动播放
  • 从C#中取消自动播放

注意:如果您的应用程序正在使用对话框,则需要调用SetWindowLong ( 签名 ),而不是仅返回false。 在这里看到更多的细节)

2.注册表

使用注册表,您可以禁用自动运行指定的驱动器号(NoDriveAutoRun)或一类驱动器( NoDriveTypeAutoRun )

  • 使用注册表来禁用AutoRun (MSDN文章)
  • 如何启用/禁用驱动器的自动运行(使用注册表)
  • Windows 7自动播放启用| 禁用

3. IQueryCancelAutoPlay

  • MSDN上IQueryCancelAutoPlay接口的参考
  • IQueryCancelAutoPlay只调用一次? (例如执行,也读取评论)
  • AutoPlayController (另一个实现,未经测试)

其他一些链接:

  • 启用和禁用AutoRun (MSDN文章)
  • 在Windows XP中自动播放:自动检测并对系统上的新设备做出反应 (一篇关于自动播放的陈旧而广泛的文章)

RegisterWindowMessage是一个Win32 API调用。 所以你将需要使用PInvoke使其工作..

using System.Runtime.InteropServices; class Win32Call { [DllImport("user32.dll")] public static extern int RegisterWindowMessage(String strMessage); } // In your application you will call Win32Call.RegisterWindowMessage("QueryCancelAutoPlay"); 

从这里 (顶部的专家交换链接)。 在这个网站上有更多的帮助,还有一些比上面更全面的例子。 但是,上述确实解决了这个问题。

一些额外的链接,可能会有所帮助:

  • 防止CD自动播放显示一些示例vb.net代码,显示CodeProject上“QueryCancelAutoPlay”的用法。
  • 在MSDN上启用和禁用AutoRun 。

试试这个代码为我工作:)欲了解更多信息查看这个参考链接: http : //www.pinvoke.net/default.aspx/user32.registerwindowmessage

 using System.Runtime.InteropServices; //provide a private internal message id private UInt32 queryCancelAutoPlay = 0; [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern uint RegisterWindowMessage(string lpString); /* only needed if your application is using a dialog box and needs to * respond to a "QueryCancelAutoPlay" message, it cannot simply return TRUE or FALSE. [DllImport("user32.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); */ protected override void WndProc(ref Message m) { //calling the base first is important, otherwise the values you set later will be lost base.WndProc (ref m); //if the QueryCancelAutoPlay message id has not been registered... if (queryCancelAutoPlay == 0) queryCancelAutoPlay = RegisterWindowMessage("QueryCancelAutoPlay"); //if the window message id equals the QueryCancelAutoPlay message id if ((UInt32)m.Msg == queryCancelAutoPlay) { /* only needed if your application is using a dialog box and needs to * respond to a "QueryCancelAutoPlay" message, it cannot simply return TRUE or FALSE. SetWindowLong(this.Handle, 0, 1); */ m.Result = (IntPtr)1; } } //WndProc