从另一个应用程序文本框中读取特定键

时间:2013-02-24 19:26:59

标签: c#

我需要知道何时在另一个应用程序中的特定文本框上按下回车键。我可以使用user32.dll找到文本框并从中写入/读取文本。但是如何获得一个特定的密钥呢?

该应用程序只是一个聊天。我的目标是当我在这个应用程序文本框上键入类似'/ time'的内容并点击回车我希望我的应用程序读取此命令并输出当前时间,例如。

以下是我必须检索应用程序及其textfield子句的句柄并编写/读取它的代码。

    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, IntPtr wParam, string lParam);

    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text);

    [DllImport("user32.dll")]
    private static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
    [DllImport("user32.Dll")]
    public static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam);

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

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string strClassName, string strWindowName);

    private IntPtr handle = IntPtr.Zero;
    private string childClassName = "TComboEdit";

    public bool findChildHandle(IntPtr hwnd, IntPtr lParam)
    {
        StringBuilder className = new StringBuilder();
        GetClassName(hwnd, className, 120);
        if (className.ToString() == childClassName)
        {
            handle = hwnd;
            return false;
        }
        return true;
    }

    private void findControl(string className, string title)
    {
        IntPtr application = IntPtr.Zero;
        application = FindWindow(className, title);
        if (application == IntPtr.Zero)
            MessageBox.Show("Aplicativo não encontrado");
        else
            EnumChildWindows(application, findChildHandle, IntPtr.Zero);
    }

    private void setTextToHandle(string msg)
    {
        SendMessage(handle, 0x000c, IntPtr.Zero, msg); //set text
        PostMessage(handle, 0x0100, new IntPtr(0x0D), IntPtr.Zero); // key down (enter)
    }

    private void getTextFromHandle()
    {
        StringBuilder t = new StringBuilder();
        SendMessage(handle, 0x0D, 100, t); //get text
        MessageBox.Show(t.ToString());
    }

0 个答案:

没有答案