2008年11月2日 星期日

c#自動偵測特定視窗並將他關閉

c#透過win32 APU偵測特定視窗並關閉
利用findwindow先取得視窗hanle 然後在用sendmessage傳送關閉的指令
特定視窗的handle可透過spy++查看

 


using System.Runtime.InteropServices;
 
    [DllImport("user32.dll")]
    public static extern int FindWindow(string strclassName, string strWindowName);
    [DllImport("user32.dll")]
    private static extern int SendMessage(
           int hWnd,   // handle to destination window
           int Msg,    // message
           int wParam, // first message parameter
           int lParam // second message parameter
     );
    const int WM_KEYDOWN = 0x0100;
    const int WM_KEYUP = 0x0101;
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_CLOSE = 0xF060;
 
    private void button1_Click(object sender, EventArgs e)
    {
        //int a= FindWindow("#32770", "LT_TEST_V1.3.exe");
        int a = FindWindow("Notepad", "未命名 - 記事本");
        listBox1.Items.Add(a);
        if (a > 0)
        {
            SendMessage(a, WM_SYSCOMMAND, SC_CLOSE, 0);
        }
    }