Enabling Menu Items

The major job in the window procedure now involves enabling and graying the options in the Edit menu, which is done when processing the WM_INITMENUPOPUP. First, the program checks to see if the Edit popup is about to be displayed. Because the position index of Edit in the menu (starting with File at 0) is 1, lParam equals 1 if the Edit popup is about to be displayed.

To determine if the Undo option can be enabled, POPPAD2 sends an EM_CANUNDO message to the edit control. The SendMessage call returns nonzero if the edit control can perform an Undo action, in which case the option is enabled; otherwise, it is grayed:

EnableMenuItem (wParam, IDM_UNDO,

SendMessage (hwndEdit, EM_CANUNDO, 0, 0L) ?

MF_ENABLED : MF_GRAYED) ;

The Paste option should be enabled only if the clipboard currently contains text. We can determine this through the IsClipboardFormatAvailable call with the CF_TEXT identifier:

EnableMenuItem (wParam, IDM_PASTE,

IsClipboardFormatAvailable (CF_TEXT) ?

MF_ENABLED : MF_GRAYED) ;

The Cut, Copy, and Clear options should be enabled only if text in the edit control has been selected. Sending the edit control an EM_GETSEL message returns a long integer containing this information:

lSelect = SendMessage (hwndEdit, EM_GETSEL, 0, 0L) ;

The low word of lSelect is the position of the first selected character; the high word of lSelect is the position of the character following the selection. If these two words are equal, no text has been selected:

if (HIWORD (lSelect) == LOWORD (lSelect))

wEnable = MF_GRAYED ;

else

wEnable = MF_ENABLED ;

The value of wEnable is then used for the Cut, Copy, and Clear options:

EnableMenuItem (wParam, IDM_CUT, wEnable) ;

EnableMenuItem (wParam, IDM_COPY, wEnable) ;

EnableMenuItem (wParam, IDM_CLEAR, wEnable) ;