2009-07-15 15 views

答えて

10

あなたに送信するハンドルがある場合は、

...Some Class... 
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] 
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); 

//I'd double check this constant, just in case 
static uint WM_CLOSE = 0x10; 

public void CloseWindow(IntPtr hWindow) 
{ 
    SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); 
} 
...Continue Class... 

ハンドルを取得するのは難しいことがあります。コントロールの子孫クラス(基本的にWinForms)にはハンドルがあり、すべてのトップレベルウィンドウをEnumWindowsで列挙できます(より高度なp/invokeが必要ですがわずかです)。

0

メモ帳を閉じたいとします。次のコードは、それを行います。

private void CloseNotepad(){ 
     string proc = "NOTEPAD"; 

     Process[] processes = Process.GetProcesses(); 
     var pc = from p in processes 
       where p.ProcessName.ToUpper().Contains(proc) 
       select p; 
     foreach (var item in pc) 
     { 
      item.CloseMainWindow(); 
     } 
    } 

考慮事項:

をメモ帳には、それがポップアップ表示されますいくつかの保存されていないテキストがある場合は、「あなたが保存しますかを......?」プロセスは何のUIを持っていない場合、それはあなたがすぐにクローズ処理を強制したい場合は、のPInvokeを移動したい場合は

item.CloseMainWindow() 

item.Kill(); 

を交換してください

'item.CloseMainWindow()' threw an exception of type 
'System.InvalidOperationException' base {System.SystemException}: 
    {"No process is associated with this object."} 

例外以下のスローダイアログまたは選択したアイテムからハンドルを使用することができます。

item.Handle; //this will return IntPtr object containing handle of process. 
+0

私は名前を付ける必要がありますか –

+0

@Hamish、*メモ帳のような他の小さなアプリケーションを閉じたい、質問を読んでする必要がありますそれを閉じるためのapplciationの? – TheVillageIdiot

+0

* @karthikは、別のアプリケーション私は*その他*を追加するように役立っていると思います – Anuya

関連する問題