Monday, June 9, 2014

C# Send text to a open command prompt

http://stackoverflow.com/questions/5929152/send-string-to-command-prompt-cmd-from-windows-form-application-using-sendmess

 [DllImport("user32")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        IntPtr hWnd = FindWindow(null, "Untitled - Notepad");

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, [MarshalAs(UnmanagedType.U4)] uint Msg, IntPtr wParam, IntPtr lParam);


        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, [MarshalAs(UnmanagedType.U4)] uint Msg, int wParam, int lParam);

        const int WM_KEYDOWN = 0x0100;
        const int WM_KEYUP = 0x0101;
        const int WM_CHAR = 0x0102;

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

        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        private const UInt32 WM_CLOSE = 0x0010;

        //public static IntPtr cmdHwnd = IntPtr.Zero;
        public static List<IntPtr> cmdHwnd = new List<IntPtr>();
     


// get all command prompt window handles to a listbox1
 public void GetWindowHandles()
        {
            listBox1.Items.Clear();
            cmdHwnd.Clear();
            foreach (IntPtr child in GetChildWindows(FindWindow(null, "WinPlusConsole")))
            {
                StringBuilder sb = new StringBuilder(100);
                GetClassName(child, sb, sb.Capacity);

                if (sb.ToString() == "ConsoleWindowClass")
                {
                    cmdHwnd.Add(child);
                    listBox1.Items.Add(child);
                }
            }
            m_iCnt = cmdHwnd.Count;
        }

//send command to a open command prompt window, cmdHwnd[0] has the window's handle
  private void btnCommand_Click(object sender, EventArgs e)
        {
            uint wparam = 0 << 29 | 0;
            string msg = textBox1.Text;
            int i = 0;
            for (i = 0; i < msg.Length; i++)
            {
                //PostMessage(child, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
                PostMessage(cmdHwnd[0], WM_CHAR, (int)msg[i], 0);
            }
            PostMessage(cmdHwnd[0], WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
        }

      /// <summary>
        /// Returns a list of child windows
        /// </summary>
        /// <param name="parent">Parent of the windows to return</param>
        /// <returns>List of child windows</returns>
        public static List<IntPtr> GetChildWindows(IntPtr parent)
        {
            List<IntPtr> result = new List<IntPtr>();
            GCHandle listHandle = GCHandle.Alloc(result);
            try
            {
                EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
                EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
            }
            finally
            {
                if (listHandle.IsAllocated)
                    listHandle.Free();
            }
            return result;
        }

        /// <summary>
        /// Callback method to be used when enumerating windows.
        /// </summary>
        /// <param name="handle">Handle of the next window</param>
        /// <param name="pointer">Pointer to a GCHandle that holds a reference to the list to fill</param>
        /// <returns>True to continue the enumeration, false to bail</returns>

        private static bool EnumWindow(IntPtr handle, IntPtr pointer)
        {
            GCHandle gch = GCHandle.FromIntPtr(pointer);
            List<IntPtr> list = gch.Target as List<IntPtr>;
            if (list == null)
            {
                throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
            }
            list.Add(handle);
            // You can modify this to check to see if you want to cancel the operation, then return a null here
            return true;
        }

        /// <summary>
        /// Delegate for the EnumChildWindows method
        /// </summary>
        /// <param name="hWnd">Window handle</param>
        /// <param name="parameter">Caller-defined variable; we use it for a pointer to our list</param>
        /// <returns>True to continue enumerating, false to bail.</returns>
        public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);


  private void btnOponWindow_Click(object sender, EventArgs e)
        {
            try
            {
                int iNo = 0;
                iNoOfWindows = iNoOfBatCmds;
                GetWindowHandles();
                if (m_iCnt > 0)
                {
                    if (iNoOfWindows > m_iCnt)
                    {
                        iNo = iNoOfWindows - m_iCnt;
                    }
                }
                else
                {
                    iNo = iNoOfWindows;
                }

                for (int i = 0; i < iNo; i++)
                {

                    // create the ProcessStartInfo using "cmd" as the program to be run,
                    // and "/c " as the parameters.
                    // Incidentally, /c tells cmd that we want it to execute the command that follows,
                    // and then exit.
                    System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/K ");

                    // The following commands are needed to redirect the standard output.
                    // This means that it will be redirected to the Process.StandardOutput StreamReader.
                    //procStartInfo.RedirectStandardOutput = true;
                    procStartInfo.UseShellExecute = true;
                    // Do not create the black window.
                    procStartInfo.CreateNoWindow = false;
                    // Now we create a process, assign its ProcessStartInfo and start it
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo = procStartInfo;
                    //ThreadStart ths = new ThreadStart(delegate() { proc.Start(); });
                    proc.Start();
                    //proc.WaitForExit();
                }
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException);
            }
            finally
            {
                GetWindowHandles();
            }
        }


   private void btnHello_Click(object sender, EventArgs e)
        {
            uint wparam = 0 << 29 | 0;
            string msg = "Hello";
            int i = 0;
            for (i = 0; i < msg.Length; i++)
            {
                //PostMessage(child, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
                //PostMessage(cmdHwnd[0], WM_CHAR, (int)msg[i], 0);
                PostMessage((IntPtr)listBox1.Items[0], WM_CHAR, (int)msg[i], 0);
            }
            PostMessage((IntPtr)listBox1.Items[0], WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
        }


No comments:

Post a Comment