MFC mouse and keyboard programming experiment

Article directory

    • 1.Preliminary knowledge
      • 1.Visual Studio program debugging method
      • 2. Operation steps of MFC message mapping
      • 3. How to handle keyboard and mouse messages in MFC programs
        • Handle mouse messages
        • Handling keyboard messages
    • 2. Experimental purpose
    • 3.Experimental content
    • 4. Code implementation
      • 1.Mouse move message
      • 2. Mouse click message
      • 3. Keyboard press message
      • 4. Print initial point
    • 5. Running results
      • 1. Display and record the position status of the mouse in the client area at all times
      • 2. The user presses the left mouse button
      • 3. The user presses the right mouse button
      • 4. The user presses the Shift key
      • 5. The user presses the Ctrl key
    • 6. Summary
      • 1. Difficulties encountered in the experiment
        • How to format the problem of printing the mouse cursor position on the screen
        • How to clear the last printed text at the cursor position when the mouse moves
        • How to print the initial cursor position
      • 2. Experience

1. Preliminary knowledge

1.Visual Studio program debugging method

Visual Studio is an integrated development environment (IDE) that can be used to develop, debug, and deploy software. In this lab, we will use Visual Studio to write and debug MFC (Microsoft Foundation Classes) applications.

In Visual Studio, you can use the following methods for program debugging:

  • Set breakpoints: Pause program execution by inserting breakpoints in the code to examine the values of variables, trace code execution paths, etc.
  • Single-step debugging: Press the F11 key at the breakpoint to execute the program line by line to understand the execution process of the program in detail.
  • Monitoring: You can monitor and track the values of variables during debugging.
  • Output window: You can use the output window to output debugging information for viewing during debugging.

2. Operation steps of MFC message mapping

Message mapping is the mechanism in MFC for handling window messages. Whenever a message occurs (such as mouse movement, keyboard press, etc.), MFC will automatically call the processing function associated with the message.

In MFC, the steps to create a message map are as follows:

  1. Declare the message processing function in the header file of the main dialog class.
  2. Add a mapping entry for the message processing function in the message mapping table.

The processing functions of message mapping need to follow specific naming rules, such as OnMouseMove(), OnKeyDown(), etc.

3. Methods of handling keyboard and mouse messages in MFC programs

In MFC programs, keyboard and mouse messages can be processed through the message mapping mechanism. Here’s how to handle common messages:

Handling mouse messages
  • Mouse movement (OnMouseMove()): Called when the mouse moves in the window.
  • Left button down (OnLButtonDown()): Called when the left mouse button is pressed.
  • Right button down (OnRButtonDown()): Called when the right button of the mouse is pressed.
Handling keyboard messages
  • Keyboard down (OnKeyDown()): Called when a key on the keyboard is pressed.

When handling keyboard messages, you can use the GetKeyState() function to check whether a specific key is pressed, such as the SHIFT key and CTRL key.

2. Experiment purpose

  1. Master the program debugging method in Visual Studio;
  2. Master the steps of MFC message mapping;
  3. Learn how to handle keyboard and mouse messages in MFC programs.

3.Experimental content

Please write a multi-document program with the following requirements:

  • Display and record the mouse position status in the client area at all times. If a click occurs, a message box is displayed to prompt the user which mouse button was pressed.
  • When the user presses the SHIFT or CTRL key, display a message box prompting the user which key was pressed

4. Code implementation

First, use the wizard to build a multi-document program framework and name the project Ex1.

Then add the corresponding events in the class wizard as follows:

1. Mouse movement message

void CEx1View::OnMouseMove(UINT nFlags, CPoint point)
{<!-- -->
CView::OnMouseMove(nFlags, point);
//CPaintDC p(this);
//Invalidate();
auto p = GetDC();
CBrush brush(RGB(255, 255, 255));
p->SelectObject( & amp;brush);
p->PatBlt(0, 0, 500, 500, WHITENESS);
CString s;
s.Format(TEXT("The mouse is at ( %d , %d )"), point.x, point.y);
p->SetDCPenColor(BLACKNESS);
p->TextOut(100, 100, s);
//RedrawWindow(nullptr, nullptr, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);
}

2. Mouse click message

void CEx1View::OnLButtonDown(UINT nFlags, CPoint point)
{<!-- -->
/*std::string s("The left mouse button is ( ");
(((s + = std::to_string(point.x)) + = ", ") + = std::to_string(point.y)) + = " ) Press!";
MessageBox(s.c_str());*/
/*CString s;
s.Format(TEXT("The left mouse button was pressed at ( %d , %d )!"), point.x, point.y);
MessageBox(s);*/
MessageBox(TEXT("Left mouse button pressed!"));
CView::OnLButtonDown(nFlags, point);
}
void CEx1View::OnRButtonDown(UINT nFlags, CPoint point)
{<!-- -->
/*CString s;
s.Format(TEXT("The right mouse button was pressed at ( %d , %d )!"), point.x, point.y);
MessageBox(s);*/
MessageBox(TEXT("Right mouse button pressed!"));
CView::OnRButtonDown(nFlags, point);
}

3. Keyboard press message

void CEx1View::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{<!-- -->
/*if (GetKeyState(VK_SHIFT) < 0)
MessageBox(TEXT("Press the Shift key!"));
else if (GetKeyState(VK_CONTROL) < 0)
MessageBox(TEXT("Press the Ctrl key!"));*/
switch(nChar)
{<!-- -->
case VK_SHIFT:
MessageBox(TEXT("Press the Shift key!"));
break;
case VK_CONTROL:
MessageBox(TEXT("Press the Ctrl key!"));
};
CView::OnKeyDown(nChar, nRepCnt, nFlags);
}

4. Print initial point

void CEx1View::OnPaint()
{<!-- -->
CPaintDC dc(this);
CPoint p;
GetCursorPos( & amp;p);
CString s;
s.Format(TEXT("The mouse is at ( %d , %d )"), p.x, p.y);
dc.TextOut(100, 100, s);
}

5. Operation results

1. Display and record the mouse position status in the client area at all times

2. The user presses the left mouse button

3. The user presses the right mouse button

4. The user presses the Shift key

5. The user presses the Ctrl key

6. Summary

1. Difficulties encountered in the experiment

How to format and print the mouse cursor position on the screen

The first thing that comes to mind is not the CString class under the MFC framework, but the standard library’s string class to format output. However, when running and debugging, the problem of mismatch of formal parameters and actual parameters and the contradiction between multi-byte and wide-byte appeared. This is because wide byte encoding is used when creating the project, and std::string is multi-byte. There is a coding conversion problem. You can use the macro TEXT is converted, but an error will be reported when using TEXT to convert the C-style string returned by std::string‘s c_str(). Therefore, the CString class under the MFC framework was finally used for formatted output.

How to clear the last printed text at the cursor position when the mouse is moving

It is only necessary to fill the entire area with white before each printing, so a CBrush object is defined to implement the function.

How to print the initial cursor position

Just rewrite the function void CEx1View::OnPaint() and use the GetCursorPos function to get the current position.

2. Experience

In this lab, I learned how to handle keyboard and mouse messages in an MFC program by using Visual Studio and the MFC framework. Through experiments, I mastered the program debugging methods of Visual Studio, including setting breakpoints, single-step debugging, etc. I also learned how to use the message mapping mechanism to handle mouse and keyboard messages, and how to use related functions and classes to implement corresponding functions.

During the experiment, I encountered some difficulties, such as how to format the output cursor position and how to clear the previous text when the mouse moves. By consulting the relevant documentation and debugging the code, I successfully solved these problems.

Through this experiment, I deeply understood the concept and operation steps of message mapping, and became more familiar with the debugging function of Visual Studio. I believe this knowledge and experience will be of great help to my future study and work.

Overall, this experiment gave me a deeper understanding of MFC mouse and keyboard programming. It not only deepened my understanding of relevant knowledge, but also exercised my problem-solving skills and hands-on practice capabilities. I believe these gains will become the basis for me to continue learning and exploring more complex program development.

Code address: https://github.com/zsc118/MFC-exercises