Search code examples
mfchovercursorceditcustom-cursor

MFC change mouse cursor on hover over CEdit control


I want to change mouse cursor to custom cursor which i added to project Resource named IDC_MY_CURSOR. i want to change mouse pointer to my cursor whenever mouse is over CEdit control only. Any idea how to do that?


Solution

  • To override the default behavior of standard controls, you will have to provide your own implementation. The most straight forward way to do this using MFC is to derive from a standard control implementation (CEdit in this case):

    CustomEdit.h:

    class CCustomEdit : public CEdit {
    public:
        CCustomEdit() {}
        virtual ~CCustomEdit() {}
    
    protected:
        DECLARE_MESSAGE_MAP()
    
    public:
        // Custom message handler for WM_SETCURSOR
        afx_msg BOOL OnSetCursor( CWnd* pWnd, UINT nHitTest, UINT message );
    };
    

    CustomEdit.cpp:

    #include "CustomEdit.h"
    
    BEGIN_MESSAGE_MAP( CCustomEdit, CEdit )
        ON_WM_SETCURSOR()
    END_MESSAGE_MAP()
    
    BOOL CCustomEdit::OnSetCursor( CWnd* pWnd, UINT nHitTest, UINT message ) {
        ::SetCursor( AfxGetApp()->LoadCursor( IDC_MY_CURSOR ) );
        // Stop processing
        return TRUE;
    }
    

    You can use this class to dynamically create a CCustomEdit control. Alternatively, you can create a standard edit control (either dynamically or through a resource script), and attach an instance of CCustomEdit to it (see DDX_Control):

    void CMyDialog::DoDataExchange( CDataExchange* pDX ) {
        DDX_Control( pDX, IDC_CUSTOM_EDIT, m_CustomEdit );
        CDialogEx::DoDataExchange( pDX );
    }