Modify the WM_COMMAND Case

You need to modify the IDM_CUT, IDM_COPY, and IDM_PASTE cases in the WM_COMMAND case to process the Edit menu commands. The IDM_CUT and IDM_COPY cases must create a global memory block, fill it with text, and copy the handle of the block to the clipboard, and the IDM_CUT case must also discard the current client-area text. The IDM_PASTE case must retrieve a handle from the clipboard, use its contents to replace the current client-area text, and request a client-area repaint.

Replace the existing IDM_CUT and IDM_COPY cases with the following statements:

case IDM_CUT:

case IDM_COPY:

if (hText != NULL) {

/* Allocate memory and copy the string to it */

if (!(hData

= GlobalAlloc(GMEM_MOVEABLE, GlobalSize (hText)))) {

OutOfMemory();

return (TRUE);

}

if (!(lpData = GlobalLock(hData))) {

GlobalFree(hData);

OutOfMemory();

return (TRUE);

}

if (!(lpszText = GlobalLock (hText))) {

OutOfMemory();

return (TRUE);

}

lstrcpy(lpData, lpszText);

GlobalUnlock(hData);

GlobalUnlock (hText);

/* Clear the current contents of the clipboard, and set

* the data handle to the new string.

*/

if (OpenClipboard(hWnd)) {

EmptyClipboard();

SetClipboardData(CF_TEXT, hData);

CloseClipboard();

}

hData = NULL;

if (wParam == IDM_CUT) {

GlobalFree (hText);

hText = NULL;

EnableMenuItem(GetMenu (hWnd), IDM_CUT, MF_GRAYED);

EnableMenuItem(GetMenu(hWnd), IDM_COPY, MF_GRAYED);

InvalidateRect (hWnd, NULL, TRUE);

UpdateWindow (hWnd);

}

}

return (TRUE);

The GlobalAlloc function allocates the global memory block used to pass text data to the clipboard. The lstrcpy function copies the client-area text into the block after the handle has been locked by the GlobalLock function. The handle must be unlocked before copying the handle to the clipboard. The EmptyClipboard function is used to remove any existing data from the clipboard.

Replace the IDM_PASTE case with the following statements:

case IDM_PASTE:

if (OpenClipboard(hWnd)) {

/* get text from the clipboard */

if (!(hClipData = GetClipboardData(CF_TEXT))) {

CloseClipboard();

break;

}

if (hText != NULL) {

GlobalFree(hText);

}

if (!(hText = GlobalAlloc(GMEM_MOVEABLE

, GlobalSize(hClipData)))) {

OutOfMemory();

CloseClipboard();

break;

}

if (!(lpClipData = GlobalLock(hClipData))) {

OutOfMemory();

CloseClipboard();

break;

}

if (!(lpszText = GlobalLock(hText))) {

OutOfMemory();

CloseClipboard();

break;

}

lstrcpy(lpszText, lpClipData);

GlobalUnlock(hClipData);

CloseClipboard();

GlobalUnlock(hText);

EnableMenuItem(GetMenu(hWnd), IDM_CUT, MF_ENABLED);

EnableMenuItem(GetMenu(hWnd), IDM_COPY, MF_ENABLED);

/* copy text to the application window */

InvalidateRect(hWnd, NULL, TRUE);

UpdateWindow(hWnd);

return (TRUE);

}

else

return (FALSE);

}

break;

The GetClipboardData function returns a handle to a global memory block. The GlobalLock function locks this handle, returning the block address that is used to make a copy of the new client-area text.