Create a transparent window in MFC

The first fully transparent
1. Set the window transparent

  //Set WS_EX_LAYERED on this window
  ::SetWindowLong(GetSafeHwnd(),
        GWL_EXSTYLE,
       ::GetWindowLongPtr(GetSafeHwnd(),GWL_EXSTYLE)|WS_EX_LAYERED);

  //Make this window 70% alpha transparent
  this->SetLayeredWindowAttributes(0,(255*70)/100,LWA_ALPHA);

2. Remove window transparency

   //Remove WS_EX_LAYERED from window style
   ::SetWindowLong(GetSafeHwnd(),
      GWL_EXSTYLE,
    ::GetWindowLongPtr(GetSafeHwnd(),GWL_EXSTYLE)&~WS_EX_LAYERED);
  //Repaint
  this->RedrawWindow();

3. Actual running effect
write picture description here
write picture description here
The second is to make the specified part transparent

OnInitialDialog中

 COLORREF maskColor = RGB(255,255,255);

 SetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE,GetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE)^0x80000);
 HINSTANCE hInst=LoadLibrary(_T("User32.DLL"));
 if(hInst)
 {
 typedef BOOL (WINAPI * MYFUNC)(HWND , COLORREF,BYTE,DWORD);
 MYFUNC fun=NULL;
 fun=(MYFUNC)GetProcAddress(hInst,"SetLayeredWindowAttributes");
 if(fun)fun(this->GetSafeHwnd(),maskColor,255,1);
 FreeLibrary(hInst);
 }

In the else function of the Opaint function

else
 {
 CRect rect;
 CPaintDC dc(this);
 GetClientRect(rect);
 dc.FillSolidRect(rect,RGB(255,255,255));
 //dc.FillSolidRect(rect,RGB(108,108,108));

 CBitmap bmp1,bmp2;
 //bmp1.LoadBitmap(IDB_B_1);
 bmp1.LoadBitmap(IDB_BITMAP6);
 bmp2.LoadBitmap(IDB_BITMAP7);

 //bmp2.LoadBitmap(IDB_B_2);
 //CPaintDC dc(this); // device context for painting
 CDC memDC;
 memDC.CreateCompatibleDC(&dc);
 CBitmap* pbmpOld;

 pbmpOld = memDC.SelectObject(&bmp1);
 dc.BitBlt(0, 0, 2000, 1500, &memDC, 0, 0, SRCPAINT);  // 注意最后一个参数

 memDC.SelectObject(&bmp2);
 dc.BitBlt(0, 0, 2000, 1500, &memDC, 0, 0, SRCAND);  // 注意最后一个参数

 memDC.SelectObject(pbmpOld);
 memDC.DeleteDC();



 CDialog::OnPaint();
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325524820&siteId=291194637