简体   繁体   English

使用SendMessage从Windows窗体应用程序将字符串发送到命令提示符(cmd)

[英]Send String to Command Prompt (cmd) from Windows Form Application using SendMessage

I read many answers on how to send command to cmd prompt. 我读了许多有关如何将命令发送到cmd提示符的答案。

But I do not want to use StreamWriter or similar stuff to input and get output. 但是我不想使用StreamWriter或类似的东西来输入和获取输出。

I want to use SendMessage to send my string or say command to the cmd prompt window. 我想使用SendMessage发送我的字符串或说命令到cmd提示窗口。

Can anyone please help on this? 有人可以帮忙吗?

Just to give detail about my application. 只是为了详细介绍我的应用程序。 1. My application is a WinForm App. 1.我的应用程序是WinForm应用程序。 2. It has 4-5 buttons. 2.它具有4-5个按钮。 3. Button1 opens the command prompt window while Button5 closes or exits the command prompt window. 3. Button1打开命令提示符窗口,而Button5关闭或退出命令提示符窗口。 4. Button 2,3,4 are command buttons. 4.按钮2、3、4是命令按钮。 When user clicks the Button2 command 1 is send to command prompt window. 当用户单击Button2命令1时,将发送到命令提示符窗口。 Similar when button 3 and 4 are clicked command 2 and command 3 are sent to the same command prompt window. 与单击按钮3和4时类似,命令2和命令3发送到同一命令提示符窗口。

Let me know if anybody has a written code which sends string to command prompt. 让我知道是否有人编写了将字符串发送到命令提示符的代码。

Thanks and regards, 谢谢并恭祝安康,

Rahul 拉胡尔

I have got the solution. 我有解决方案。
I used PostMessage(). 我使用了PostMessage()。
Cmd has handle and you can send string to it. Cmd具有句柄,您可以向其发送字符串。
I was just struggling to find the right way to get the handle. 我只是在努力寻找正确的方法来处理问题。
Now I got one. 现在我得到了。

/*
 * Created by SharpDevelop.
 * User: Rahul
 * Date: 5/12/2011
 * Time: 1:49 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace GetChildWindows
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
    [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;

    public static IntPtr cmdHwnd = IntPtr.Zero;

    public MainForm()
    {
        //
        // The InitializeComponent() call is required for Windows Forms designer support.
        //
        InitializeComponent();

        //
        // TODO: Add constructor code after the InitializeComponent() call.
        //

        foreach (IntPtr child in GetChildWindows(FindWindow(null, "WinPlusConsole")))
        {
            StringBuilder sb = new StringBuilder(100);
            GetClassName(child, sb, sb.Capacity);


            if (sb.ToString() == "ConsoleWindowClass")
            {
//                  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(child, WM_CHAR, (int)msg[i], 0);
//                  }
//                  PostMessage(child, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);

                cmdHwnd = child;
            }
        }

}

/// <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);





    void BtnHelloClick(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, WM_CHAR, (int)msg[i], 0);
                }
                PostMessage(cmdHwnd, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
    }

    void BtnCommandClick(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, WM_CHAR, (int)msg[i], 0);
                }
                PostMessage(cmdHwnd, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
    }

    void TextBox1TextChanged(object sender, EventArgs e)
    {

    }
}
} 


Thanks to all! 谢谢大家!

It seems unlikely that you would be able to achieve this with SendMessage() . 您似乎不太可能能够使用SendMessage()实现此目的。 SendMessage() requires a window handle and I don't believe that cmd.exe has a suitable window handle to receive the message. SendMessage()需要一个窗口句柄,我不相信cmd.exe具有合适的窗口句柄来接收消息。

My advice is to look for a method that solves your problem rather than deciding what solution you want and trying to make it fit the problem. 我的建议是寻找一种可以解决问题的方法,而不是确定所需的解决方案并尝试使其适合问题。

its not clear from your explenation (at least not to me) why you cant use streamWriter in the scenario you describe. 从您的专长(至少对我而言)不清楚,为什么您不能在所描述的场景中使用streamWriter。 can you elaborate on that? 你能详细说明一下吗?

i'd check out the Process class for talking to other programs via stdin/out 我会签出Process类,以便通过stdin / out与其他程序对话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#for .NET中从Windows窗体应用程序发送命令提示符参数? - How Do I Send Command Prompt Arguments from a Windows Form Application in C# for .NET? 打开命令提示符并从Windows窗体应用程序执行命令 - open Command Prompt and execute commands from Windows Form Application 在Windows窗体应用程序的后台在cmd中运行命令 - running a command in the cmd in the background of a windows form application 如何检测正在执行应用程序的上下文? 无论是从命令提示符还是从Windows窗体内部 - How to detect the context from which an application is being executed? Whether from Command Prompt or from within a Windows Form 如何使用sendmessage(C#)向cmd.exe发送退格键 - How to send backspace using sendmessage(C#) to cmd.exe Windows CMD /命令提示符的维度是什么? - What are the dimensions of the Windows CMD/Command Prompt? 从 HTML 或命令提示链接向独立的 Unity 应用程序发送消息? - Send message to standalone Unity application from HTML or command prompt link? 使用C#Windows窗体通过CMD执行telnet命令 - Executing telnet Command through CMD using c# windows form 是否从PsExec命令检索cmd提示输出? - Retrieve cmd prompt output from PsExec command? 从控制台应用程序获取响应(Windows中的命令提示符) - Get Response from Console Application (command prompt in windows)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM