关于ModifyStyle或ModifyStyleEx无法改变控件属性的解决方法【原创】

类别:VC语言 点击:0 评论:0 推荐:

CWnd* pWnd为你控件的指针,LPCTSTR lpszClassName是你控件的类名,比如编辑框是"Edit",按钮是"Button",详情可以使用SPY++查看.

BOOL ModifyControlStyle(CWnd* pWnd,LPCTSTR lpszClassName,DWORD dwRemove,DWORD dwAdd,DWORD dwRemoveEx,DWORD dwAddEx)
{
 CWnd* pParentWnd = pWnd->GetParent();

 CFont* pFont = pWnd->GetFont();

 CString strText;
 pWnd->GetWindowText(strText);

 {
  // 在此添加保存控件其他属性的代码,我只保存了字体和文字
 }

 CRect rcWindow;
 pWnd->GetWindowRect(&rcWindow);
 pParentWnd->ScreenToClient(rcWindow);

 DWORD dwNewStyle = (pWnd->GetStyle() & ~dwRemove) | dwAdd;
 DWORD dwNewStyleEx = (pWnd->GetExStyle() & ~dwRemoveEx) | dwAddEx;

 UINT nID = pWnd->GetDlgCtrlID();

 pWnd->ShowWindow(SW_HIDE);
 pWnd->DestroyWindow();

 BOOL bResult = pWnd->CreateEx(dwNewStyleEx,lpszClassName,strText,dwNewStyle,rcWindow,pParentWnd,nID);

 pWnd->SetFont(pFont);

 return bResult;
}

测试代码:

void CAboutDlg::OnButton()
{
 CWnd* pWnd = GetDlgItem(IDC_EDIT1);

 if(pWnd->GetStyle() & ES_PASSWORD)
 {
  ModifyControlStyle(pWnd,"Edit",ES_PASSWORD,0,0,0);
 }
 else
 {
  ModifyControlStyle(pWnd,"Edit",0,ES_PASSWORD,0,0);
 }
}

本文地址:http://com.8s8s.com/it/it204.htm