c#/.NET を使用して Windows の自動再生機能を無効にする方法を知っている人はいますか?
4 に答える
自動再生を無効/抑制する良い方法を探している他のすべての人のための簡単な要約。これまでのところ、プログラムで自動再生を無効にする 3 つの方法を見つけました。
- QueryCancelAutoPlay メッセージのインターセプト
- レジストリの使用
- COM インターフェイスIQueryCancelAutoPlayの実装
最後に、3 番目の方法を選択し、IQueryCancelAutoPlay インターフェイスを使用しました。これは、他の方法にはいくつかの重大な欠点があったためです。
- 最初のメソッド (QueryCancelAutoPlay) は、アプリケーション ウィンドウがフォアグラウンドにある場合にのみ自動再生を抑制することができました。これは、フォアグラウンド ウィンドウのみがメッセージを受け取るためです。
- アプリケーション ウィンドウがバックグラウンドにある場合でも、レジストリで自動再生を構成すると機能しました。欠点: 有効にするには、現在実行中のexplorer.exeを再起動する必要があったため、これは自動再生を一時的に無効にする解決策ではありませんでした。
実装例
1.QueryCancelAutoPlay
注: アプリケーションでダイアログ ボックスを使用している場合は、 false を返すだけでなく、SetWindowLong ( signature )を呼び出す必要があります。詳しくはこちらをご覧ください)
2.レジストリ
レジストリを使用して、指定したドライブ文字 (NoDriveAutoRun) またはドライブのクラス ( NoDriveTypeAutoRun ) に対して AutoRun を無効にすることができます。
3.IQueryCancelAutoPlay
- MSDNの IQueryCancelAutoPlayインターフェイスのリファレンス
- IQueryCancelAutoPlay は 1 回だけ呼び出されますか? (実装例、コメントもお読みください)
- 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");
ここから(上部の Experts-Exchange リンク)。そのサイトには、上記よりももう少し包括的な例を含む追加のヘルプがあります。ただし、上記は問題を解決します。
役に立つかもしれないいくつかの追加リンク:
- 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