Hi,
I am trying to get control of an opened command prompt.Is there any possible way to do that. So that i can directly pass arguments ie commands to command prompt using c# coding.
( I tried using process but only killing the process is working so that already opened command prompt can be closed using the c# code.)

You need to get a MainwindowHandle and activate it using P/invoke SetForegroundWindow().

[DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);


        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process proc = (from n in System.Diagnostics.Process.GetProcesses()
                                               where n.ProcessName == "cmd"
                                               select n).FirstOrDefault();
            if (proc == null)
            {
                MessageBox.Show("No such a process.");
            }
            else
            {
                SetForegroundWindow(proc.MainWindowHandle);
                SendKeys.Send("Dir{enter}");
                
            }
        }

Yes I tried the same code but control is not going to running command prompt.But Every thing is executing without error and control is coming again to form itself even after the button click event(in which i pasted your code).Can you explain it little more elaborately.

Hello adatapost,
Its working but SendKeys.Send("Dir{enter}");
is comming in command prompt like dddddddiiiiiiiiiirrrrrrrrrrrrrr some time.
any way thanks for your reply

Yes It worked only thing you want to take care is use Caps.So no issue will happen .
Example SendKeys.Send("Dir{enter}");
instead Use

SendKeys.Send("DIR{enter}");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.