c#如何使用PostMessage发送@ -Char?

时间:2018-10-22 15:59:04

标签: c# windows automation character

我自动将登录帐户登录到我的电子邮件帐户。我使用User32.DLL中的Postmessage函数,因为我的主要目标之一是该程序可以在后台运行而不弹出。很烦人。

所以,我的错误是,我无法发送'@'-Char。通常不会,因为未按下STRG + ALT键。我研究了一下,一个论坛说不可能用Postmessage模仿'STR + ALT + AnyChar',但是我也认为CapsLock钥匙也有问题,所以我认为这是可能的。也许你们可以帮帮我。这是我的一部分代码:

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

    [DllImport("user32.dll")]
    static extern bool SetCursorPos(int X, int Y);

    [DllImport("kernel32.dll")]
    public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern short VkKeyScan(char ch);

    [DllImport("user32.dll")]
    static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

    const int PROCESS_WM_READ = 0x0010;
    const uint WM_LBUTTONDOWN = 0x201;
    const uint WM_LBUTTONUP = 0x202;
    const uint WM_KEYDOWN = 0x0100;
    const uint WM_KEYUP = 0x0101;

    const int KEYEVENTF_EXTENDEDKEY = 0x1;
    const int KEYEVENTF_KEYUP = 0x2;
    const int KEYEVENTF_KEYDOWN = 0x0;

    public static Keys ConvertCharToVirtualKey(char ch)
    {
        short vkey = VkKeyScan(ch);
        Keys retval = (Keys)(vkey & 0xff);
        int modifiers = vkey >> 8;
        if ((modifiers & 1) != 0) retval |= Keys.Shift;
        if ((modifiers & 2) != 0) retval |= Keys.Control;
        if ((modifiers & 4) != 0) retval |= Keys.Alt;
        return retval;
    }
    //In this function lies the problem
    static void SendText(string texty)
    {

        char[] characters = texty.ToCharArray();

        Process[] processes = Process.GetProcessesByName("firefox");
        foreach (Process p in processes)
        {
            if (p.ProcessName == "firefox")
            {

                for (int i = 0; i != characters.Length; i++)
                {
                    if (characters[i] == '@')
                    {
                        //DO SOME OTHER STUFF M8Y
                    }
                    else
                    {

                        PostMessage(p.MainWindowHandle, WM_KEYUP, (int)ConvertCharToVirtualKey(characters[i]), 0);

                    }

                    System.Threading.Thread.Sleep(5);
                    if (Control.IsKeyLocked(Keys.CapsLock))
                    {
                        keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
                        keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
                        System.Threading.Thread.Sleep(60);
                    }

                }

            }

        }
        System.Threading.Thread.Sleep(35);
    }

0 个答案:

没有答案