Evan.zz
Evan.zz

Reputation: 165

MFC Accessing lparam throw expection

I have 2 CEdit controlsin the view, both of them have same ID.

In the parent window, i created ON_EN_CHANGE handle to catch their editing message. Since editing either of those edit box will fire up a message to the handle function, I want to find a way to distinguish which edit control does it come from.

So in my handle function, i used GetCurrentMessage() to obtain the MSG object. and it lparam should be the pointer of calling edit control.

But when i modify it, it returns exception says "access violation reading location"

    //onCreate function
    text1->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | ES_MULTILINE | WS_VSCROLL, \
    CRect(300,200,400,300), this, 1);
    text2->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | ES_MULTILINE | WS_VSCROLL, \
    CRect(100, 100, 300, 200), this, 1);

    //parent class
    BEGIN_MESSAGE_MAP(CScratchView, CView)
    ...
    ON_EN_CHANGE(1, chandle)
    END_MESSAGE_MAP()

    //Message handle function
    void CScratchView::chandle()
    {
        const MSG* lst = GetCurrentMessage();
        if (lst->lParam != NULL) {
        CEdit* sa = (CEdit*) lst->lParam;
        sa->SetWindowTextW(_T("what"));
    }

Since both edit control share same handle function, i need to know which one is calling. I'm not sure this is the right way to do it. but i think this should work.

Any suggestion would be great. thanks

Upvotes: 1

Views: 81

Answers (1)

Sid S
Sid S

Reputation: 6125

You can use lParam like this:

CEdit *sa = (CEdit *) CWnd::FromHandle(lst->lParam);

It would probably be smarter to give the two edit controls different IDs (you use 1 for both). Then you can inspect LOWORD(lst->wParam) which contains the control ID :

text1->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | ES_MULTILINE | WS_VSCROLL, 
              CRect(300,200,400,300), this, 100);

text2->Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | ES_MULTILINE | WS_VSCROLL, 
              CRect(100, 100, 300, 200), this, 101);

...

ON_EN_CHANGE(100, chandle)
ON_EN_CHANGE(101, chandle)

Also note that IDOK is 1. Start your control IDs at 100 or higher.

Upvotes: 1

Related Questions