Select a rectangle on the screen

Everything else that doesn't fall into one of the other PB categories.
AZJIO
Addict
Addict
Posts: 1316
Joined: Sun May 14, 2017 1:48 am

Re: Select a rectangle on the screen

Post by AZJIO »

Made global. After the first call, hBmp always contains a handle and will be deleted before the call.

Code: Select all

Global hBmp, PDC

Procedure HBitmapFromScreen(X, Y, W, H)
	If hBmp
		SelectObject_(PDC, hBmp)
		DeleteObject_(hBmp)
		DeleteDC_(PDC)
	EndIf
	If Not HDC
		HDC = GetDC_(0)
	EndIf
	hBmp = CreateCompatibleBitmap_(HDC, W, H)
	PDC = CreateCompatibleDC_(HDC)
	SelectObject_(PDC, hBmp)
	BitBlt_(PDC, 0, 0, W, H, HDC, X, Y, #SRCCOPY)
EndProcedure
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: Select a rectangle on the screen

Post by Mijikai »

Example:

Code: Select all

Procedure.i BitmapFromDC(Handle.i,X.i,Y.i,W.i,H.i)
  Protected.i hdc,hbm,hold
  hdc = CreateCompatibleDC_(Handle)
  If hdc
    hbm = CreateCompatibleBitmap_(Handle,W,H)
    If hbm
      hold = SelectObject_(hdc,hbm)
      If hold
        If BitBlt_(hdc,#Null,#Null,W,H,Handle,X,Y,#SRCCOPY)
          SelectObject_(hdc,hold)
          DeleteDC_(hdc)
          ProcedureReturn hbm
        EndIf
        SelectObject_(hdc,hold)
      EndIf
      DeleteObject_(hbm)
    EndIf
    DeleteDC_(hdc)
  EndIf
  ProcedureReturn #Null
EndProcedure
AZJIO
Addict
Addict
Posts: 1316
Joined: Sun May 14, 2017 1:48 am

Re: Select a rectangle on the screen

Post by AZJIO »

I can't delete Bitmap since it is used to save to a file.
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: Select a rectangle on the screen

Post by Mijikai »

I showed how to deselect the bitmap so that it doesnt get leaked once you lose control over the DC.
AZJIO
Addict
Addict
Posts: 1316
Joined: Sun May 14, 2017 1:48 am

Re: Select a rectangle on the screen

Post by AZJIO »

Code: Select all

hold = SelectObject_(hdc,hbm)
is it necessary inside one program? Will this cause a problem in other programs?

I read in the help that it is always necessary to return the original object
An application should always replace a new object with the original, default object after it has finished drawing with the new object.
User avatar
Mijikai
Addict
Addict
Posts: 1360
Joined: Sun Sep 11, 2016 2:17 pm

Re: Select a rectangle on the screen

Post by Mijikai »

AZJIO
Addict
Addict
Posts: 1316
Joined: Sun May 14, 2017 1:48 am

Re: Select a rectangle on the screen

Post by AZJIO »

He says that if you control your DC, then you can not delete it right away, but delete it later. This is the strategy I chose. This can only be a problem if someone is using this code and specifically using my DC. I hope the user himself will decide when to delete and he will not mix one with the other.
Post Reply