Applications: Using the System Clipboard in Windows Mobile

Recently, someone on the MSDN forum asked about using ‘Cut, Copy and Paste’ operation in their application and I thought it makes for a worthy post. Using the system clipboard is pretty easy. This article has everything you need know. Basically, the clipboard operations are performed in the following order:

Copy
1. Open Clipboard
2. Empty Clipboard’s contents
3. Set the Clipboard’s data
4. Close Clipboard

Paste
1. Open Clipboard
2. Check if Clipboard data is available
3. Get the Clipboard data
4. Close Clipboard

Cut operation is the same as Copy but you also delete the data from the source. It is upto your application to do that.

The sample application that I built handles only ‘text’ clipboard data and consists of two multiline edit boxes, the top one serving as the source and the bottom as destination for all clipboard operations. Lets look at how the application works, and then we’ll look at the code:

For Copy, Paste and Cut, the following handlers are called:

//DoCopy
void DoCopy(HWND hDlg)
{
    BOOL ret;
    HWND hTemp;
    TCHAR *pData = NULL;
    int size = 0;

    hTemp = GetDlgItem(hDlg, IDC_EDIT_TOP);

    _ASSERT(hTemp != NULL);
    if (!hTemp)
        return;

    //get the size of text in the edit box
    size = SendMessage(hTemp, WM_GETTEXTLENGTH, 0, 0);

    pData = (TCHAR*)LocalAlloc(LPTR, size*sizeof(TCHAR) + 1);

    _ASSERT(pData != NULL);
    if (!pData)
        return;

    SendMessage(hTemp, WM_GETTEXT, (WPARAM)size+1, (LPARAM)pData);

    ret = OpenClipboard(hDlg);

    _ASSERT(ret != 0);
    if (ret == 0)
        return;

    EmptyClipboard();

    if (!SetClipboardData(CF_UNICODETEXT, pData))
    {
        _ASSERT(FALSE);
    }

    CloseClipboard();
}

//DoPaste
void DoPaste(HWND hDlg)
{
    BOOL ret;
    TCHAR *pData = NULL;

    ret = OpenClipboard(hDlg);
    _ASSERT(ret != 0);
    if (ret == 0)
        return;

    ret = IsClipboardFormatAvailable(CF_UNICODETEXT);
    if (ret == 0)
    {
        CloseClipboard();
        return;
    }

    pData = (TCHAR*)GetClipboardData(CF_UNICODETEXT);

    if (pData)
    {
        SendMessage(GetDlgItem(hDlg, IDC_EDIT_BOTTOM), WM_SETTEXT, 0, (LPARAM)pData);
    }

    CloseClipboard();
}

//DoCut
void DoCut(HWND hDlg)
{
    DoCopy(hDlg);

    SendMessage(GetDlgItem(hDlg, IDC_EDIT_TOP), WM_SETTEXT, 0, (LPARAM)(TEXT("")));
}

The code is simple enough to understand. All the Clipboard functions can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *