2

iam trying to paste the data gathered from the clipboard in a textbox (C#)

In this case i copy something into the clipboard

Clipboard.SetText("Hello, clipboard"); 

How can i do that at the exact moment that clipboard has something,(or when the users does a ctrl+c) perform a copy event into a textbox?

i have tried with this code;My textbox is tbData:

private void tbData_TextChanged(object sender, EventArgs e)
{
    if (Clipboard.ContainsText(TextDataFormat.Text))
    {
        tbData.Text = Clipboard.GetText();
        Clipboard.Clear();
    }
}

but i get this exception:

Requested Clipboard operation did not succeed

abatishchev
  • 98,240
  • 88
  • 296
  • 433
WickedJenn
  • 43
  • 1
  • 7
  • Have you looked at this: http://stackoverflow.com/questions/621577/clipboard-event-c-sharp – John Koerner Dec 06 '13 at 04:35
  • From memory, you need to dirty your hand a bit and go into native calls. I should have an example I can post later today if you want for an app I wrote that monitors the clipboard ... – Noctis Dec 06 '13 at 04:45

2 Answers2

2

You'll have to wire-up an event handler for clipboard update event. But this required using P/Invoke to DllImport("user32.dll") to get to event. See this article http://www.fluxbytes.com/csharp/how-to-monitor-for-clipboard-changes-using-addclipboardformatlistener/

Then you can do this.....

//register clipboard change
            YourAppName.ClipboardUpdate += new EventHandler(ClipboardChanged);
private void ClipboardChanged(object sender, EventArgs e)

    {
        IDataObject iData = Clipboard.GetDataObject();

        //clipboard not empty and these are the formats I am only interested in
        if (iData.GetDataPresent(DataFormats.UnicodeText) || iData.GetDataPresent(DataFormats.Text) || iData.GetDataPresent(DataFormats.Html)) 
        { 
         //do work
        }
     }    
Markus
  • 420
  • 3
  • 7
1

Try this code

if (Clipboard.ContainsText(TextDataFormat.Html))
{
    returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
    Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
Sajid Hussain
  • 63
  • 2
  • 10