Search code examples
c++mfcclipboardrtf

How to write a Table to clipboard in MFC (or just c++) to be pasted into word?


I'm writing an MFC program and would like to be able to output some data in table form, preferably by writing it to the clipboard and then pasting it out into word.

So far, I have looked into using the rich text format to draw a table. Which I have successfully done into a .rtf file as follows:

std::string s = "{\\rtf \\par \\trowd \\trqc\\trgaph108\\trrh280\\trleft36"
    "\\clbrdrt\\brdrth \\clbrdrl\\brdrth \\clbrdrb\\brdrdb"
    "\\clbrdrr\\brdrdb \\cellx3636\\clbrdrt\\brdrth"
    "\\clbrdrl\\brdrdb \\clbrdrb\\brdrdb \\clbrdrr\\brdrdb"
    "\\cellx7236\\clbrdrt\\brdrth \\clbrdrl\\brdrdb"
    "\\clbrdrb\\brdrdb \\clbrdrr\\brdrdb \\cellx10836\\pard \\intbl "
    "First Cell"
    " \\cell \\pard \\intbl "
    "Second Cell"
    " \\cell \\pard \\intbl "
    "Third Cell"
    " \\cell \\pard \\intbl \\row"
    "\\trowd \\trqc\\trgaph108\\trrh280\\trleft36 \\clbrdrt\\brdrdb"
    "\\clbrdrl\\brdrth \\clbrdrb \\brdrsh\\brdrs \\clbrdrr\\brdrdb"
    "\\cellx3636\\clbrdrt\\brdrdb \\clbrdr \\brdrdb"
    "\\clbrdrb\\brdrsh\\brdrs \\clbrdrr\\brdrdb"
    "\\cellx7236\\clbrdrt\\brdrdb \\clbrdr \\brdrdb"
    "\\clbrdrb\\brdrsh\\brdrs \\clbrdrr\\brdrdb \\cellx10836\\pard"
    "\\intbl "
    "Fourth Cell"
    " \\cell \\pard \\intbl "
    "Fifth Cell"
    " \\cell \\pard \\intbl "
    "Sixth Cell"
    "\\cell \\pard"
    "\\intbl \\row \\pard}";
ofstream file("f.rtf");
if(file.is_open())
{ file << s; file.close}

I would like to write the table instead to clipboard with something like:

::OpenClipboard(NULL);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size());
if (!hg){
    CloseClipboard();
    return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size());
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);

but I can't find a clipboard format for rich text. Is it possible to do it this way? Are there any MFC tricks to do this?


Solution

  • You need to register the format (or get the already registered format):

    CLIPFORMAT cfRTF = RegisterClipboardFormat(_T("Rich Text Format"));