SendKeys Ctrl + C到外部应用程序(文本到剪贴板)

时间:2016-02-09 16:56:15

标签: c# c++ vb.net clipboard sendkeys

我有一个应用程序,它作为托盘图标放在系统托盘中。我已经注册了一个热键,当按下它时将捕获任何应用程序中的当前文本选择,即使在Web浏览器中也是如此。

我的方法是发送密钥组合{Ctlr + C}来复制文本。然后访问剪贴板并使用我自己的应用程序中的文本。

我在VB.NET中编程,但是对C#的任何帮助,甚至是使用Win32_Api的C ++都会受到高度赞赏。

我使用AutoHotkey,在那里,我有一个访问剪贴板文本的脚本,工作正常。

Pause::
clipboard =  ; Start off empty to allow ClipWait to detect when the text has arrived.
Send ^c
ClipWait, 2  ; Wait for the clipboard to contain text.
if ErrorLevel
{
    ;Do nothing after 2 seconds timeout
    return
}
Run https://translate.google.com/#auto/es/%clipboard%
return

由于AutoHotkey是开源的,我下载了代码并尝试尽可能多地复制 ClipWait 的行为。

我的代码大多数时间都有效,但有时会有一个重要的延迟。我无法访问剪贴板和win32函数 IsClipboardFormatAvailable()持续返回False for While。当我尝试从可编辑的TextBox中专门从Google Chrome进行复制时,会发生这种情况。

我尝试了很多不同的东西,包括使用.Net Framework剪贴板类。我读到的问题可能是运行命令的线程没有设置为STA,所以我做到了。在我的绝望中,我也放了一个计时器,但没有完全解决问题。

我还读了一个钩子来监视剪贴板的选项,但我想避免这种情况,除非它是唯一的方法。

这是我的VB.NET代码:

Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports Hotkeys
Public Class Form1
    Public m_HotKey As Keys = Keys.F6

    Private Sub RegisterHotkeys()
        Try
            Dim alreaydRegistered As Boolean = False
            ' set the hotkey:
            ''---------------------------------------------------
            ' add an event handler for hot key pressed (or could just use Handles)
            AddHandler CRegisterHotKey.HotKeyPressed, AddressOf hotKey_Pressed
            Dim hkGetText As HotKey = New HotKey("hkGetText",
                            HotKey.GetKeySinModificadores(m_HotKey),
                            HotKey.FormatModificadores(m_HotKey.ToString),
                            "hkGetText")
            Try
                CRegisterHotKey.HotKeys.Add(hkGetText)
            Catch ex As HotKeyAddException
                alreaydRegistered = True
            End Try
        Catch ex As Exception
            CLogFile.addError(ex)
        End Try
    End Sub

    Private Sub hotKey_Pressed(sender As Object, e As HotKeyPressedEventArgs)
        Try
            Timer1.Start()
        Catch ex As Exception
            CLogFile.addError(ex)
        End Try
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        RegisterHotkeys()
    End Sub

    Function copyText() As String
        Dim result As String = String.Empty
        Clipboard.Clear()
        Console.WriteLine("Control + C")
        SendKeys.SendWait("^c")
        Dim Attempts As Integer = 100
        Do While Attempts > 0
            Try
                result = GetText()
                If result = String.Empty Then
                    Attempts -= 1
                    'Console.WriteLine("Attempts {0}", Attempts)
                    Thread.Sleep(100)
                Else
                    Attempts = 0
                End If

            Catch ex As Exception
                Attempts -= 1
                Console.WriteLine("Attempts Exception {0}", Attempts)
                Console.WriteLine(ex.ToString)
                Threading.Thread.Sleep(100)
            End Try
        Loop
        Return result
    End Function

#Region "Win32"

    <DllImport("User32.dll", SetLastError:=True)>
    Private Shared Function IsClipboardFormatAvailable(format As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport("User32.dll", SetLastError:=True)>
    Private Shared Function GetClipboardData(uFormat As UInteger) As IntPtr
    End Function

    <DllImport("User32.dll", SetLastError:=True)>
    Private Shared Function OpenClipboard(hWndNewOwner As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport("User32.dll", SetLastError:=True)>
    Private Shared Function CloseClipboard() As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True)>
    Private Shared Function GlobalLock(hMem As IntPtr) As IntPtr
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True)>
    Private Shared Function GlobalUnlock(hMem As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport("Kernel32.dll", SetLastError:=True)>
    Private Shared Function GlobalSize(hMem As IntPtr) As Integer
    End Function

    Private Const CF_UNICODETEXT As UInteger = 13UI
    Private Const CF_TEXT As UInteger = 1UI

#End Region

    Public Shared Function GetText() As String
        If Not IsClipboardFormatAvailable(CF_UNICODETEXT) AndAlso Not IsClipboardFormatAvailable(CF_TEXT) Then
            Return Nothing
        End If

        Try
            If Not OpenClipboard(IntPtr.Zero) Then
                Return Nothing
            End If

            Dim handle As IntPtr = GetClipboardData(CF_UNICODETEXT)
            If handle = IntPtr.Zero Then
                Return Nothing
            End If

            Dim pointer As IntPtr = IntPtr.Zero

            Try
                pointer = GlobalLock(handle)
                If pointer = IntPtr.Zero Then
                    Return Nothing
                End If

                Dim size As Integer = GlobalSize(handle)
                Dim buff As Byte() = New Byte(size - 1) {}

                Marshal.Copy(pointer, buff, 0, size)

                Return Encoding.Unicode.GetString(buff).TrimEnd(ControlChars.NullChar)
            Finally
                If pointer <> IntPtr.Zero Then
                    GlobalUnlock(handle)
                End If
            End Try
        Finally
            CloseClipboard()
        End Try
    End Function

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Try
            Timer1.Stop()
            Dim ThreadA As Thread
            ThreadA = New Thread(AddressOf Me.copyTextThread)
            ThreadA.SetApartmentState(ApartmentState.STA)
            ThreadA.Start()
        Catch ex As Exception
            CLogFile.addError(ex)
        End Try
    End Sub

    Sub copyTextThread()
        Dim result As String = copyText()
        If result <> String.Empty Then
            MsgBox(result)
        End If
    End Sub
End Class

我还搜索了其他类似的问题而没有最终解决我的问题:

Send Ctrl+C to previous active window

How do I get the selected text from the focused window using native Win32 API?

2 个答案:

答案 0 :(得分:1)

在这种情况下,VB.Net实际上提供了一种解决问题的方法。它被称为SendKeys.Send(<key>),您可以将其与参数SendKeys.Send("^(c)")一起使用。根据{{​​3}}

,这会将Ctrl + C发送到计算机

答案 1 :(得分:0)

将AutoHotkey放回壁橱,放弃了对IsClipboardFormatAvailable

的需求

使用Microsoft完成的全局键盘挂钩: RegisterHotKey function 效果非常好,
 唯一需要注意的是,它本身不适用于F6,你需要Alt +,Ctrl +或Shift +

下载示例winform应用并自行查看:

https://code.msdn.microsoft.com/CppRegisterHotkey-7bd897a8 C ++ https://code.msdn.microsoft.com/CSRegisterHotkey-e3f5061e C#https://code.msdn.microsoft.com/VBRegisterHotkey-50af3179 VB.Net

如果以上链接腐烂,我已在 this answer 中包含C#源代码。

策略:

  1. 监视哪个是最后一个活动窗口

  2. (可选)保存剪贴板的当前状态(以便以后恢复)

  3. 将SetForegroundWindow()设置为最后一个活动窗口的句柄

  4. SendKeys.Send("^c");

  5. (可选)重置保存在2

  6. 中的剪贴板值

    代码:

    以下是我修改Microsoft Sample项目的方法,用以下代码替换mainform.cs构造函数:

    namespace CSRegisterHotkey
    {
    public partial class MainForm : Form
    {
        [DllImport("User32.dll")]
        static extern int SetForegroundWindow(IntPtr point);
    
        WinEventDelegate dele = null;
        delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
    
        [DllImport("user32.dll")]
        static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
    
        private const uint WINEVENT_OUTOFCONTEXT = 0;
        private const uint EVENT_SYSTEM_FOREGROUND = 3;
    
        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();
    
        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    
        //Another way if SendKeys doesn't work (watch out for this with newer operating systems!)
        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
    
        //----
    
        HotKeyRegister hotKeyToRegister = null;
    
        Keys registerKey = Keys.None;
    
        KeyModifiers registerModifiers = KeyModifiers.None;
    
        public MainForm()
        {
            InitializeComponent();
    
            dele = new WinEventDelegate(WinEventProc);
            IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
        }
    
        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            IntPtr handle = IntPtr.Zero;
            StringBuilder Buff = new StringBuilder(nChars);
            handle = GetForegroundWindow();
    
            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                lastHandle = handle;
                return Buff.ToString();
            }
            return null;
        }
    
        public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
        {
            txtLog.Text += GetActiveWindowTitle() + "\r\n";
        }
    

    在mainform中将HotKeyPressed事件更改为此优点:

    void HotKeyPressed(object sender, EventArgs e)
    {
        //if (this.WindowState == FormWindowState.Minimized)
        //{
        //    this.WindowState = FormWindowState.Normal;
        //}
        //this.Activate();
    
        //Here is the magic
        SendCtrlCKey(lastHandle);
    }
    
    private void SendCtrlCKey(IntPtr mainWindowHandle)
    {
        SetForegroundWindow(mainWindowHandle);
        //IMPORTANT - Wait for the window to regain focus
        Thread.Sleep(300); 
        SendKeys.Send("^c");
    
        //Comment out the next 3 lines in Release
    #if DEBUG 
        this.Activate();
        MessageBox.Show(Clipboard.GetData(DataFormats.Text).ToString());
        SetForegroundWindow(mainWindowHandle);
    #endif
    }
    
    //Optional example of how to use the keybd_event encase with newer Operating System the SendKeys doesn't work
    private void SendCtrlC(IntPtr hWnd)
    {
        uint KEYEVENTF_KEYUP = 2;
        byte VK_CONTROL = 0x11;
        SetForegroundWindow(hWnd);
        keybd_event(VK_CONTROL, 0, 0, 0);
        keybd_event(0x43, 0, 0, 0); //Send the C key (43 is "C")
        keybd_event(0x43, 0, KEYEVENTF_KEYUP, 0);
        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);// 'Left Control Up
    }
    

    警告:

      
        
    1. 如果您的应用程序适用于各种键盘的国际使用,则使用SendKeys.Send可能会产生不可预测的结果,应该避免使用。参考:Simulating Keyboard Input&lt; - 方法不起作用!!!
    2.   
    1. 对于操作系统更改感到不满,如下所述:https://superuser.com/questions/11308/how-can-i-determine-which-process-owns-a-hotkey-in-windows
    2. 研究:

      Detect active window changed using C# without polling
      Simulating CTRL+C with Sendkeys fails
      Is it possible to send a WM_COPY message that copies text somewhere other than the Clipboard?
      Global hotkey release (keyup)? (WIN32 API)
      C# using Sendkey function to send a key to another application
      How to perform .Onkey Event in an Excel Add-In created with Visual Studio 2010?
      How to get selected text of any application into a windows form application
      Clipboard event C#
      How do I monitor clipboard content changes in C#?

      享受:

      enter image description here