使用Winapi获取/设置剪贴板文本

时间:2014-04-07 19:42:26

标签: vb.net api clipboard clipboarddata

我喜欢使用Windows API做同样的事情。

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = System.Windows.Forms.Clipboard.GetText
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        System.Windows.Forms.Clipboard.SetText(TextBox1.Text)
    End Sub

我看了一眼:http://www.pinvoke.net/default.aspx/user32/GetClipboardData.html 但我不太确定如何使用它以及如何将文本设置到剪贴板。 谁可以帮助我?

2 个答案:

答案 0 :(得分:2)

与此相似:

Copy result to clipboard

我将其转换为VB.net版本,因为问题标记为:

Public Class Form1
    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
    Public Shared Function OpenClipboard(ByVal hWndNewOwner As IntPtr) As Boolean
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
    Public Shared Function CloseClipboard() As Boolean
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
    Public Shared Function SetClipboardData(ByVal uFormat As UIntPtr, ByVal data As IntPtr) As Boolean
    End Function

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        OpenClipboard(IntPtr.Zero)
        Dim yourString = "Hello World!"
        Dim ptr As String = Marshal.StringToHGlobalUni(yourString)
        SetClipboardData(13, ptr)
        CloseClipboard()

        Marshal.FreeHGlobal(ptr)
    End Sub
End Class

答案 1 :(得分:0)

有问题的源C#版本以一种可能导致崩溃的模糊方式出现错误。

如果您遇到问题,请点击此处链接到我对原始主题的回复,并提及更强大的替代方案:SetClipboardData + StringToHGlobalUni is a bad combination.