可编辑文本

MFC自带的CListCtrl不可编辑,要使其可编辑,其基本思想是,创建listctrl时,创建一个编辑框(edit)并隐藏, 当我们双击(这里没考虑先选中一项再点击选中行进入编辑的情况,方法类似)listctrl时,在表格某格的上方显示出这个编辑框,在这个编辑框中输入数据,当编辑完成后(即失去焦点)再将编辑框中的东西传到listctrl中。其实现代码如下(*.h,*.cpp复制后可直接使用,如你觉得有帮助,请留下你脚印,谢谢!):

 

头文件 MyList.h

#pragma once
#include "afxcmn.h"
#include "afxwin.h"

#define ID_EDIT 1001

class CMyEdit :
 public CEdit
{
public:
 CMyEdit(void);
public:
 ~CMyEdit(void);
public:
 DECLARE_MESSAGE_MAP()
public:
 afx_msg void OnKillFocus(CWnd* pNewWnd);
public:
 afx_msg void OnSetFocus(CWnd* pOldWnd);
public:
 void SetParent(CWnd* pWnd);
 CString m_strText;
 int m_nItem;
 int m_nSubItem;
 CBrush   m_brush; 
 COLORREF m_TextBkColor; 
 COLORREF m_TextColor;

 CWnd* m_pPar;
public:
 afx_msg HBRUSH CtlColor(CDC* /*pDC*/, UINT /*nCtlColor*/);
};


class CMyList :
 public CListCtrl
{
public:
 CMyList(void);
public:
 ~CMyList(void);
 CMyEdit m_Edit;
protected:
 virtual void PreSubclassWindow();
public:
 DECLARE_MESSAGE_MAP()
public:
 afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
};

 

实现文件 MyList.cpp

#include "StdAfx.h"
#include "MyList.h"

CMyEdit::CMyEdit(void)
{
 m_TextBkColor=RGB(255,255,0);
 m_TextColor = RGB(255,0, 2555);
 m_brush.CreateSolidBrush(m_TextBkColor);
}

CMyEdit::~CMyEdit(void)
{
}
BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
 ON_WM_KILLFOCUS()
 ON_WM_SETFOCUS()
 ON_WM_CTLCOLOR()
 ON_WM_CTLCOLOR_REFLECT()
END_MESSAGE_MAP()

void CMyEdit::OnKillFocus(CWnd* pNewWnd)
{
 CEdit::OnKillFocus(pNewWnd);

 GetWindowText(m_strText);
 ((CMyList*)m_pPar)->SetItemText(m_nItem, m_nSubItem, m_strText);
 this->ShowWindow(SW_HIDE);
}

void CMyEdit::OnSetFocus(CWnd* pOldWnd)
{
 CEdit::OnSetFocus(pOldWnd);
 SetWindowText(m_strText);
}

void CMyEdit::SetParent(CWnd* pWnd)
{
 m_pPar = pWnd;
}

HBRUSH CMyEdit::CtlColor(CDC* pDC, UINT /*nCtlColor*/)
{
 HBRUSH   hbr; 
 pDC->SetTextColor(m_TextColor);
 pDC->SetBkColor(m_TextBkColor);
 hbr   =   (HBRUSH)m_brush;

 return hbr;
}

CMyList::CMyList(void)
{
}

CMyList::~CMyList(void)
{
}

void CMyList::PreSubclassWindow()
{
 m_Edit.Create(WS_CHILD|WS_CLIPSIBLINGS|WS_EX_TOOLWINDOW|WS_BORDER,
  CRect(0,40,10,50),this,ID_EDIT);
 m_Edit.SetParent(this);


 CListCtrl::PreSubclassWindow();
}
BEGIN_MESSAGE_MAP(CMyList, CListCtrl)
 ON_WM_LBUTTONDBLCLK()
END_MESSAGE_MAP()

void CMyList::OnLButtonDblClk(UINT nFlags, CPoint point)
{
 CListCtrl::OnLButtonDblClk(nFlags, point);

 LVHITTESTINFO lvhti;

 lvhti.pt = point;
 lvhti.flags=LVHT_ONITEMLABEL;
 this->SubItemHitTest(&lvhti);
 int nItem = lvhti.iItem;
 int nSubItem = lvhti.iSubItem;

 if (lvhti.flags & LVHT_ONITEMLABEL)
 {
  CRect rectCell;
  this->GetSubItemRect(nItem, nSubItem, LVIR_LABEL,rectCell);
  m_Edit.m_nItem = nItem;
  m_Edit.m_nSubItem = nSubItem;
  m_Edit.m_strText = this->GetItemText(nItem, nSubItem);
  m_Edit.MoveWindow(&rectCell, TRUE);
  m_Edit.SetFocus();
  m_Edit.SetSel(0, -1); 
  m_Edit.ShowWindow(SW_SHOW);
 }
}


你可能感兴趣的:(可编辑文本)