C#控制其它程序

时间:2021-11-12 16:47:48

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
        private static extern void SetForegroundWindow(IntPtr hwnd);

        
        private void button1_Click(object sender, EventArgs e)
        {
            var hwndPhoto = FindWindow(null, "XMind"); //查找拍照程序的句柄【任务管理器中的应用程序名称】  

            if (hwndPhoto != IntPtr.Zero)
            {
                SetForegroundWindow(hwndPhoto);    //将UcDemo程序设为当前活动窗口  
                SendKeys.Send("^o");
                Clipboard.SetDataObject(@"D:\思维导图\文档\基础数据改造.xmind");
                System.Threading.Thread.Sleep(200);   //暂停500毫秒  
                SendKeys.Send("^v");
                System.Threading.Thread.Sleep(200);   //暂停500毫秒
                SendKeys.Send("~");
                System.Threading.Thread.Sleep(500);   //暂停500毫秒
                SendKeys.Send("^p");
                System.Threading.Thread.Sleep(200);   //暂停500毫秒
                SendKeys.Send("~");
            }
            else
            {
                MessageBox.Show("没有启动 XMind");
            }
        }