Page 1 of 1

How to use Clipboard in a correct way?

Posted: Mon Apr 22, 2013 7:04 am
by bulue
Hello.
I use wxWidges-2.9.4,compile with Unicode,in Windows 7.

I show a piece of my code below:

Code: Select all

#include <wx/clipbrd.h>

void MyFrame1::OnCopyClick( wxCommandEvent& event )
{
	wxString str= m_textCtrl1->GetValue();
	wxOpenClipboard();
	wxEmptyClipboard();
	wxSetClipboardData(wxDF_TEXT,str.mb_str(wxConvUTF8));
	wxCloseClipboard();
	event.Skip();
}

void MyFrame1::OnPasteClick( wxCommandEvent& event )
{
	wxOpenClipboard();
	wxString str = wxString((char*)wxGetClipboardData(wxDF_TEXT),wxConvUTF8);
	wxCloseClipboard();
	m_textCtrl1->SetValue(str);
	event.Skip();
}
In my wx program, I has 2 buttons (a copy_ button,a paste_ button ) and a textctrl (named m_textCtrl1).

I can click copy_ and paste_ button to copy chinese character in this program correctlly.
If i click copy_ button to copy value from textctrl, then i use (ctrl + v) to paste to other editors like txt,ms-excel.But it's garbled!!
if i copy some text from other editors,then i click patse_ button to paste it to m_textctrl1.it's garbled too!!

How to use Clipboard in a correct way?

regards.
bulue

Re: How to use Clipboard in a correct way?

Posted: Mon Apr 22, 2013 10:03 am
by doublemax
From the docs:

Code: Select all

// Read some text
if (wxTheClipboard->Open())
{
  if (wxTheClipboard->IsSupported( wxDF_TEXT ))
  {
    wxTextDataObject data;
    wxTheClipboard->GetData( data );
    wxMessageBox( data.GetText() );
  }
wxTheClipboard->Close();
}
As Windows itself doesn't use UTF-8 anywhere, code like this is usually wrong in any case:

Code: Select all

wxString str = wxString((char*)wxGetClipboardData(wxDF_TEXT),wxConvUTF8);

Re: How to use Clipboard in a correct way?

Posted: Mon Apr 22, 2013 12:22 pm
by bulue
Thank you,doublemax.

I have read the docs of wxClipboard. Then I changed my code, now it works correctlly!!!

Re: How to use Clipboard in a correct way?

Posted: Mon Apr 22, 2013 4:34 pm
by eranif
One more thing about wxClipboard:

You should consider calling wxTheClipboard->Flush() when your application exits, or else the copied data in the clipboard will get lost when your application exits.

http://docs.wxwidgets.org/2.9.4/classwx ... 33f291f932

Eran