如何在MFC应用程序中放置一个按钮?

Gho*_*ost 2 mfc button visual-c++

我的mfc程序在客户区域中绘制了以下形状 - 现在我想在其旁边放置一个按钮以重新排列形状.

在此输入图像描述

我知道我可以使用工具栏或菜单按钮,但有没有办法可以在框旁边放置一个按钮?这样的事情:

在此输入图像描述

Gaz*_*yer 5

您需要做的就是创建一个CButton,并适当地定位它.

//.h
#define MYBUTTONID 10000 //or whatever doesn't conflict with your existing resources

public class CMyVew : public CView
{
    CButton m_Button;

    virtual void OnInitialUpdate();
    void RepositionButton();
}

//.cpp
void CMyVew::OnInitialUpdate()
{
   //this creates the actual button GUI window
   m_Button.Create("Rearrange", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0,0,0,0), this, MYBUTTONID);
   RepositionButton();
}

void CMyVew::RepositionButton()
{
    //work out button position you need
    m_Button.MoveWindow(x, y, width, height);
}
Run Code Online (Sandbox Code Playgroud)

请注意,该按钮仅创建一次并负责绘图本身.你不需要担心它OnDraw()或类似的东西.

您唯一需要担心的是按钮应该移动位置.这就是我分离出这个RepositionButton()功能的原因.例如,如果您正在使用a CScrollView并且用户滚动,则按钮窗口不知道这一点,因此您需要对滚动事件做出反应并调用RepositionButton()

您可以通过添加ON_BTN_CLICKED消息映射来响应按钮的消息,就像对待任何其他按钮一样.