如何使用keybd_event模拟Ctrl A + Ctrl C.

时间:2013-01-18 08:57:07

标签: c# keyboard-events

如何使用keybd_event模拟 Ctrl - A + Ctrl - C ?< / p>

因为我在webbrowser表单上模拟ctrl a + ctrl c来复制剪贴板上的整个内容。我使用SendKeys.SendWait,但它没有复制整个内容!

3 个答案:

答案 0 :(得分:10)

这应该有效

[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

public const int KEYEVENTF_EXTENDEDKEY = 0x0001; //Key down flag
public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag
public const int VK_LCONTROL = 0xA2; //Left Control key code
public const int A = 0x41; //A key code
public const int C = 0x43; //C key code

public static void PressKeys()
{
    // Hold Control down and press A
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
    keybd_event(A, 0, KEYEVENTF_EXTENDEDKEY, 0);
    keybd_event(A, 0, KEYEVENTF_KEYUP, 0);
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);

    // Hold Control down and press C
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
    keybd_event(C, 0, KEYEVENTF_EXTENDEDKEY, 0);
    keybd_event(C, 0, KEYEVENTF_KEYUP, 0);
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);
}

答案 1 :(得分:0)

你可以发射Cntrl-A + Cntrl-C事件,对吗?但由于某种原因,您没有将所有网页文本复制到剪贴板?

我不太了解做Cntrl-A + Cntrl-C事件,而且我也不清楚你想做什么,但是我给了它最好的镜头并提出了一些抓住的东西来自网页的所有文本,并通过按钮点击事件将其复制到剪贴板...(现在显然你想要使用你的Cntrl-A + Cntrl-C)。同样出于调试目的,我将剪贴板文本放在.txt文件中,以便您可以仔细检查。

我也在使用HTML Agility Pack。你可以从http://htmlagilitypack.codeplex.com/

获得

<强> CODE

    private void btnClip_Click(object sender, EventArgs e)
    {
        string address = "http://animalrights.about.com/";
        string text = "";

        // Retrieve resource as a stream
        Stream data = client.OpenRead(new Uri(address)); //client here is a WebClient

        //create document
        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        document.Load(data);

        //receive all the text fields
        foreach (HtmlNode node in document.DocumentNode.SelectNodes("//child::p"))
        {
            text += node.InnerText + "\n\n";
        }

        Clipboard.SetText(text);
        string path = @"C:\Users\David\Documents\Visual Studio 2012\Projects\CopyToClipBoard\CopyToClipBoard\bin\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        // Create the file.
        using (FileStream fs = File.Create(path, 1024))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes(text);

            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        //destroy data object
        data.Close();
        data.Dispose();
    }

打开记事本检查文件

答案 2 :(得分:0)

Windows输入模拟器使这非常容易。

  

Windows输入模拟器提供简单的.NET(C#)接口   使用Win32 SendInput方法模拟键盘或鼠标输入。所有   Interop的功能是为您完成的,并且有一个简单的编程模型   用于发送多次击键。

Nuget包 - &gt; Install-Package InputSimulator

https://inputsimulator.codeplex.com/