Question

I like to do the same thing using the 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

I looked here: http://www.pinvoke.net/default.aspx/user32/GetClipboardData.html but I am not so sure how to use it and also how to set the text to the clipboard. Anyone who can help me out?

Was it helpful?

Solution

Pretty similar with this one:

Copy result to clipboard

And I converted it to VB.net version since the question is tagged with it:

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

OTHER TIPS

The source C# version in question was buggy in an obscure way that can cause crashes.

If you experience problems, then here's a link to my response on the original topic, with a reference to a more robust alternative: SetClipboardData + StringToHGlobalUni is a bad combination.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top