Copier le contenu d'une Form dans une Picturebox

Résolu
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 - Modifié le 7 sept. 2019 à 10:43
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 - 18 sept. 2019 à 12:37
Bonjour,
J'utilise le code que j'ai trouvé ici
https://www.codeproject.com/Articles/23234/VB6-Save-Form-Image-To-File?fid=992036
Public Sub SaveFormImageToPictureBox(ByRef ContainerForm As Form, ByRef PictureBoxControl As PictureBox)
  Dim FormInsideWidth As Long
  Dim FormInsideHeight As Long
  Dim PictureBoxLeft As Long
  Dim PictureBoxTop As Long
  Dim PictureBoxWidth As Long
  Dim PictureBoxHeight As Long
  
  With PictureBoxControl
    .Visible = True
    .AutoSize = False
    .AutoRedraw = True
    .BorderStyle = 0 'No border
    
          'Store PictureBox Original Size and location Values
    PictureBoxHeight = .Height: PictureBoxWidth = .Width
    PictureBoxLeft = .Left: PictureBoxTop = .Top
    
    'Make PictureBox to size to inside of form.
    .Align = vbAlignTop: .Align = vbAlignLeft
    DoEvents
        FormInsideHeight = .Height: FormInsideWidth = .Width
    
    'Restore PictureBox Original location
    .Align = vbAlignNone
    .Height = FormInsideHeight: .Width = FormInsideWidth
    .Left = PictureBoxLeft: .Top = PictureBoxTop
    
    ContainerForm.AutoRedraw = False
    DoEvents
    
    'Copy Form Image to Picture Box
    BitBlt .hdc, 0, 32, _
    FormInsideWidth / Screen.TwipsPerPixelX, _
    FormInsideHeight / Screen.TwipsPerPixelY, _
    ContainerForm.hdc, 0, 0, _
    vbSrcCopy
 
    DoEvents
    ContainerForm.AutoRedraw = True
    DoEvents

  End With
End Sub
Il fonctionne très bien sauf que le résultat dans la picturebox est plus grand que la form, exemple d'une form


et le résultat dans la picturebox



Où est l'erreur ?

8 réponses

NHenry Messages postés 15113 Date d'inscription vendredi 14 mars 2003 Statut Modérateur Dernière intervention 22 avril 2024 159
7 sept. 2019 à 11:15
Ben la fenêtre semble être bien retranscrite, je ne vois pas d'erreur.
Les champs textes sont de la même couleur et avec le même contenu.
0
JeuDuTaquin Messages postés 249 Date d'inscription mardi 4 juillet 2017 Statut Membre Dernière intervention 31 mai 2023 7
7 sept. 2019 à 11:40
Salut,
L'erreur n'en est pas réellement une, car la fenêtre Form a été prise dans son entier… incluant la zone "menu" avec "Héberger" et "help"...
Il te faut donc supprimer la hauteur de ce menu (fixe), en partie haute…. et tu auras la bonne hauteur.
0
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 2
Modifié le 14 sept. 2019 à 10:03
Bonjour,
J'avais perdu ceci de vue et comme je ne reçois pas de mail de notification ...

L'image résultante est en effet trop haute mais aussi trop large.
Théoriquement il suffirait en effet de réduire hauteur et largeur mais de combien ?
Quand je fais Alt+Impr écran j'ai bien toute la fenêtre dans le presse papier !
N'est-il pas possible de capturer toute la fenêtre telle qu'on la voit quand le logiciel tourne ?
0
JeuDuTaquin Messages postés 249 Date d'inscription mardi 4 juillet 2017 Statut Membre Dernière intervention 31 mai 2023 7
Modifié le 14 sept. 2019 à 19:25
Salut Hervé,
Dans ton code je n'aime pas le .Width et le .Height, car tu ne prends pas en compte les valeurs "Scale" de la fenêtre… Donc, préfère une capture de largeur ou de hauteur de fenêtre en utilisant .ScaleHeight et .ScaleWidht.
Tu auras moins de surprises en capturant les dimensions de la frame.
Normalement le HDC de la frame prend en compte le menu ! (qui n'est pas affiché sur ta capture car non inclue dans le rafraîchissement)
Utilise plutôt ce code:
Public Function CaptureWindow(ByVal hWndSrc As Long, _
    ByVal bClient As Boolean, ByVal LeftSrc As Long, _
    ByVal TopSrc As Long, ByVal WidthSrc As Long, _
    ByVal HeightSrc As Long) As Picture
'(…)
      SavePicture CaptureForm(Me), OpenDialog.Filename '<nom du fichier
'(…)
Public Function CaptureForm(frm As Form) As Picture
'
' Capture the entire form.
'
With frm
    Set CaptureForm = CaptureWindow(.hwnd, False, 0, 0, _
            .ScaleX(.Width, vbTwips, vbPixels), _
            .ScaleY(.Height, vbTwips, vbPixels))
End With
End Function


Pour tout l'écran:
' Returns a handle to the Desktop window.  The desktop
' window covers the entire screen and is the area on top
' of which all icons and other windows are painted.
Private Declare Function GetDesktopWindow Lib "user32" () As Long
'(…)
      SavePicture CaptureScreen, OpenDialog.Filename '<nom du fichier
'(…)
Public Function CaptureScreen() As Picture
Dim hWndScreen As Long
'
' Get a handle to the desktop window.
hWndScreen = GetDesktopWindow()
'
' Capture the entire desktop.
'
With Screen
    Set CaptureScreen = CaptureWindow(hWndScreen, False, 0, 0, _
            .Width \ .TwipsPerPixelX, .Height \ .TwipsPerPixelY)
End With
End Function

Et tu sera plus dans les clous…

Pour réduire la fenêtre, tu joues… au jugé, sur des constantes (-180...) en hauteur et largeur...
0
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 2
15 sept. 2019 à 11:52
Bonjour et merci pour ta réponse mais je ne comprends pas ton code pour la fenêtre.
Tu as 2 Function et un seul End Function
CaptureWindow appelle CaptureForm et CaptureForm appelle CaptureWindow
Peux-tu expliquer ?
0
JeuDuTaquin Messages postés 249 Date d'inscription mardi 4 juillet 2017 Statut Membre Dernière intervention 31 mai 2023 7
Modifié le 16 sept. 2019 à 10:38
Salut Hervé,

Oui, effectivement, la fonction CaptureWindows n'est pas une GDI, donc il te manque la routine et tous les enfants qui vont avec:
Option Explicit
Option Base 0
'
' This module contains several routines for capturing windows into a
' picture.  All routines have palette support.
'
' CreateBitmapPicture   - Creates a picture object from a bitmap and palette.
' CaptureWindow         - Captures any window given a window handle.
' CaptureActiveWindow   - Captures the active window on the desktop.
' CaptureForm           - Captures the entire form.
' CaptureClient         - Captures the client area of a form.
' CaptureScreen         - Captures the entire screen.
' PrintPictureToFitPage - prints any picture as big as possible on the page.
'
Private Type PALETTEENTRY
    peRed   As Byte
    peGreen As Byte
    peBlue  As Byte
    peFlags As Byte
End Type

Private Type LOGPALETTE
    palVersion       As Integer
    palNumEntries    As Integer
    palPalEntry(255) As PALETTEENTRY  ' Enough for 256 colors
End Type
         
Private Type Guid
    Data1    As Long
    Data2    As Integer
    Data3    As Integer
    Data4(7) As Byte
End Type

Private Type RECT
    Left   As Long
    top    As Long
    Right  As Long
    Bottom As Long
End Type

Private Type PicBmp
    Size As Long
    Type As Long
    hBmp As Long
    hPal As Long
    Reserved As Long
End Type

Private Const RASTERCAPS As Long = 38
Private Const RC_PALETTE As Long = &H100
Private Const SIZEPALETTE As Long = 104
'
' DC = Device Context
'
' Creates a bitmap compatible with the device associated
' with the specified DC.
Private Declare Function CreateCompatibleBitmap Lib "gdi32" ( _
    ByVal hdc As Long, ByVal nWidth As Long, _
    ByVal nHeight As Long) As Long

' Retrieves device-specific information about a specified device.
Private Declare Function GetDeviceCaps Lib "gdi32" ( _
    ByVal hdc As Long, ByVal iCapabilitiy As Long) As Long

' Retrieves a range of palette entries from the system palette
' associated with the specified DC.
Private Declare Function GetSystemPaletteEntries Lib "gdi32" ( _
    ByVal hdc As Long, ByVal wStartIndex As Long, _
    ByVal wNumEntries As Long, lpPaletteEntries As PALETTEENTRY) _
    As Long

' Creates a memory DC compatible with the specified device.
Private Declare Function CreateCompatibleDC Lib "gdi32" ( _
    ByVal hdc As Long) As Long

' Creates a logical color palette.
Private Declare Function CreatePalette Lib "gdi32" ( _
    lpLogPalette As LOGPALETTE) As Long

' Selects the specified logical palette into a DC.
Private Declare Function SelectPalette Lib "gdi32" ( _
    ByVal hdc As Long, ByVal HPALETTE As Long, _
    ByVal bForceBackground As Long) As Long

' Maps palette entries from the current logical
' palette to the system palette.
Private Declare Function RealizePalette Lib "gdi32" ( _
    ByVal hdc As Long) As Long

' Selects an object into the specified DC. The new
' object replaces the previous object of the same type.
' Returned is the handle of the replaced object.
Private Declare Function SelectObject Lib "gdi32" ( _
    ByVal hdc As Long, ByVal hObject As Long) As Long

' Performs a bit-block transfer of color data corresponding to
' a rectangle of pixels from the source DC into a destination DC.
Private Declare Function BitBlt Lib "gdi32" ( _
    ByVal hDCDest As Long, ByVal XDest As Long, _
    ByVal YDest As Long, ByVal nWidth As Long, _
    ByVal nHeight As Long, ByVal hDCSrc As Long, _
    ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) _
    As Long

' Retrieves the DC for the entire window, including title bar,
' menus, and scroll bars. A window DC permits painting anywhere
' in a window, because the origin of the DC is the upper-left
' corner of the window instead of the client area.
Private Declare Function GetWindowDC Lib "user32" ( _
    ByVal hwnd As Long) As Long

' Retrieves a handle to a display DC for the Client area of
' a specified window or for the entire screen.  You can use
' the returned handle in subsequent GDI functions to draw in
' the DC.
Private Declare Function GetDC Lib "user32" ( _
    ByVal hwnd As Long) As Long

' Releases a DC, freeing it for use by other applications.
' The effect of the ReleaseDC function depends on the type
' of DC.  It frees only common and window DCs.  It has no
' effect on class or private DCs.
Private Declare Function ReleaseDC Lib "user32" ( _
    ByVal hwnd As Long, ByVal hdc As Long) As Long

' Deletes the specified DC.
Private Declare Function DeleteDC Lib "gdi32" ( _
    ByVal hdc As Long) As Long

' Retrieves the dimensions of the bounding rectangle of the
' specified window. The dimensions are given in screen
' coordinates that are relative to the upper-left corner
' of the screen.
Private Declare Function GetWindowRect Lib "user32" ( _
    ByVal hwnd As Long, lpRect As RECT) As Long

' Returns a handle to the Desktop window.  The desktop
' window covers the entire screen and is the area on top
' of which all icons and other windows are painted.
Private Declare Function GetDesktopWindow Lib "user32" () As Long

' Returns a handle to the foreground window (the window
' the user is currently working). The system assigns a
' slightly higher priority to the thread that creates the
' foreground window than it does to other threads.
Private Declare Function GetForegroundWindow Lib "user32" () As Long

' Creates a new picture object initialized according to a PICTDESC
' structure, which can be NULL, to create an uninitialized object if
' the caller wishes to have the picture initialize itself through
' IPersistStream::Load.  The fOwn parameter indicates whether the
' picture is to own the GDI picture handle for the picture it contains,
' so that the picture object will destroy its picture when the object
' itself is destroyed.  The function returns an interface pointer to the
' new picture object specified by the caller in the riid parameter.
' A QueryInterface is built into this call.  The caller is responsible
' for calling Release through the interface pointer returned - phew!
Private Declare Function OleCreatePictureIndirect _
    Lib "olepro32.dll" (PicDesc As PicBmp, RefIID As Guid, _
    ByVal fPictureOwnsHandle As Long, ipic As IPicture) As Long
Public Function CreateBitmapPicture(ByVal hBmp As Long, _
        ByVal hPal As Long) As Picture
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' CreateBitmapPicture
'    - Creates a bitmap type Picture object from a bitmap and palette.
'
' hBmp
'    - Handle to a bitmap
'
' hPal
'    - Handle to a Palette
'    - Can be null if the bitmap doesn't use a palette
'
' Returns
'    - Returns a Picture object containing the bitmap
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
Dim r   As Long
Dim Pic As PicBmp
'
' IPicture requires a reference to "Standard OLE Types"
'
Dim ipic          As IPicture
Dim IID_IDispatch As Guid
'
' Fill in with IDispatch Interface ID
'
With IID_IDispatch
    .Data1 = &H20400
    .Data4(0) = &HC0
    .Data4(7) = &H46
End With
'
' Fill Pic with the necessary parts.
'
With Pic
    .Size = Len(Pic)          ' Length of structure
    .Type = vbPicTypeBitmap   ' Type of Picture (bitmap)
    .hBmp = hBmp              ' Handle to bitmap
    .hPal = hPal              ' Handle to palette (may be null)
End With
'
' Create the Picture object.
r = OleCreatePictureIndirect(Pic, IID_IDispatch, 1, ipic)
'
' Return the new Picture object.
'
Set CreateBitmapPicture = ipic
End Function



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' CaptureWindow
'    - Captures any portion of a window.
'
' hWndSrc
'    - Handle to the window to be captured
'
' bClient
'    - If True CaptureWindow captures from the bClient area of the
'      window
'    - If False CaptureWindow captures from the entire window
'
' LeftSrc, TopSrc, WidthSrc, HeightSrc
'    - Specify the portion of the window to capture
'    - Dimensions need to be specified in pixels
'
' Returns
'    - Returns a Picture object containing a bitmap of the specified
'      portion of the window that was captured
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Function CaptureWindow(ByVal hWndSrc As Long, _
    ByVal bClient As Boolean, ByVal LeftSrc As Long, _
    ByVal TopSrc As Long, ByVal WidthSrc As Long, _
    ByVal HeightSrc As Long) As Picture

Dim hDCMemory       As Long
Dim hBmp            As Long
Dim hBmpPrev        As Long
Dim r               As Long
Dim hDCSrc          As Long
Dim hPal            As Long
Dim hPalPrev        As Long
Dim RasterCapsScrn  As Long
Dim HasPaletteScrn  As Long
Dim PaletteSizeScrn As Long
Dim LogPal          As LOGPALETTE
'
' Get the proper Device Context (DC) depending on the value of bClient.
'
If bClient Then
    hDCSrc = GetDC(hWndSrc)       'Get DC for Client area.
Else
    hDCSrc = GetWindowDC(hWndSrc) 'Get DC for entire window.
End If
'
' Create a memory DC for the copy process.
'
hDCMemory = CreateCompatibleDC(hDCSrc)
'
' Create a bitmap and place it in the memory DC.
'
hBmp = CreateCompatibleBitmap(hDCSrc, WidthSrc, HeightSrc)
hBmpPrev = SelectObject(hDCMemory, hBmp)
'
' Get the screen properties.
'
RasterCapsScrn = GetDeviceCaps(hDCSrc, RASTERCAPS)   'Raster capabilities
HasPaletteScrn = RasterCapsScrn And RC_PALETTE       'Palette support
PaletteSizeScrn = GetDeviceCaps(hDCSrc, SIZEPALETTE) 'Palette size
'
' If the screen has a palette make a copy and realize it.
'
If HasPaletteScrn And (PaletteSizeScrn = 256) Then
    '
    ' Create a copy of the system palette.
    '
    LogPal.palVersion = &H300
    LogPal.palNumEntries = 256
    r = GetSystemPaletteEntries(hDCSrc, 0, 256, LogPal.palPalEntry(0))
    hPal = CreatePalette(LogPal)
    '
    ' Select the new palette into the memory DC and realize it.
    '
    hPalPrev = SelectPalette(hDCMemory, hPal, 0)
    r = RealizePalette(hDCMemory)
End If
'
' Copy the on-screen image into the memory DC.
'
r = BitBlt(hDCMemory, 0, 0, WidthSrc, HeightSrc, hDCSrc, _
    LeftSrc, TopSrc, vbSrcCopy)
'
' Remove the new copy of the on-screen image.
'
hBmp = SelectObject(hDCMemory, hBmpPrev)
'
' If the screen has a palette get back the
' palette that was selected in previously.
'
If HasPaletteScrn And (PaletteSizeScrn = 256) Then
    hPal = SelectPalette(hDCMemory, hPalPrev, 0)
End If
'
' Release the DC resources back to the system.
'
r = DeleteDC(hDCMemory)
r = ReleaseDC(hWndSrc, hDCSrc)
'
' Create a picture object from the bitmap
' and palette handles.
'
Set CaptureWindow = CreateBitmapPicture(hBmp, hPal)
End Function

Public Function CaptureScreen() As Picture
Dim hWndScreen As Long
'
' Get a handle to the desktop window.
hWndScreen = GetDesktopWindow()
'
' Capture the entire desktop.
'
With Screen
    Set CaptureScreen = CaptureWindow(hWndScreen, False, 0, 0, _
            .Width \ .TwipsPerPixelX, .Height \ .TwipsPerPixelY)
End With
End Function

Public Function CaptureForm(frm As Form) As Picture
'
' Capture the entire form.
'
With frm
    Set CaptureForm = CaptureWindow(.hwnd, False, 0, 0, _
            .ScaleX(.Width, vbTwips, vbPixels), _
            .ScaleY(.Height, vbTwips, vbPixels))
End With
End Function

Public Function CaptureClient(frm As Form) As Picture
'
' Capture the client area of the form.
'
With frm
    Set CaptureClient = CaptureWindow(.hwnd, True, 0, 0, _
            .ScaleX(.ScaleWidth, .ScaleMode, vbPixels), _
            .ScaleY(.ScaleHeight, .ScaleMode, vbPixels))
End With
End Function

Public Function CaptureActiveWindow() As Picture
Dim hWndActive As Long
Dim RectActive As RECT
'
' Get a handle to the active/foreground window.
' Get the dimensions of the window.
'
hWndActive = GetForegroundWindow()
Call GetWindowRect(hWndActive, RectActive)
'
' Capture the active window.
'
With RectActive
    Set CaptureActiveWindow = CaptureWindow(hWndActive, False, 0, 0, _
            .Right - .Left, .Bottom - .top)
End With
End Function

0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 2
16 sept. 2019 à 11:13
Bonjour et merci beaucoup,
Entretemps en cherchant CaptureWindow j'ai trouvé ici http://www.thescarms.com/VBasic/capture.aspx
C'est beaucoup mieux que ce que j'avais fait car j'ai aussi l'en-tête (la barre supérieure) de la fenêtre.
Le seul petit détail est qu'elle est encore trop large : il capture plus que nécessaire à gauche et à droite, en bas aussi.

0
JeuDuTaquin Messages postés 249 Date d'inscription mardi 4 juillet 2017 Statut Membre Dernière intervention 31 mai 2023 7
17 sept. 2019 à 01:43
Salut Hervé,

Oui, j'ai remarqué ce bogue de dimension de fenêtre dès l'apparition du Windows 7.
Le mode de fenêtrage entre le compilé et la fenêtre du compilateur est différente.
Il faut donc "adapter" la capture à la fenêtre en mode compilé… en ajoutant les marges en largeur ou hauteur.
Ces marges restent fixes et donneront le même résultat sur toutes les machines… mais, sans garanties pour les systèmes XP et inférieurs.
Le code se basant sur le DC général de l'écran est donc peu fiable.
0
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 2
17 sept. 2019 à 10:15
OK, ça fonctionne parfaitement maintenant.
J'ai comparé la fenêtre réelle avec sa capture : elle est 7 pixels plus grande à gauche, à droite et en bas, j'ai donc fait
SavePicture CaptureWindow(.hwnd, False, 7, 0,
.ScaleX(.Width, vbTwips, vbPixels) - 14,
.ScaleY(.Height, vbTwips, vbPixels) - 7), LocalFile
Un tout grand merci, problème résolu.
0
JeuDuTaquin Messages postés 249 Date d'inscription mardi 4 juillet 2017 Statut Membre Dernière intervention 31 mai 2023 7
18 sept. 2019 à 02:57
Merci Hervé pour le retour.
Amuse-toi bien.
0
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 2
Modifié le 18 sept. 2019 à 12:21
Bonjour,
J'ai quand même encore un petit problème : la marge diffère d'une fenêtre à l'autre.
J'ai plusieurs forms dans le même programme; pour certaines la capture est 7 pixels plus grande à gauche, à droite et en bas, pour d'autres c'est 3.
4 pixels c'est peu mais suffisant pour qu'on se rende compte que quelque chose cloche.

Je pensais a priori que c'était proportionnel à la taille de la fenêtre mais c'est l'inverse : 7 pixels de plus pour une fenêtre de 300 pixels, 3 pixels de plus pour une de 1.000 pixels.
Pourtant quand je copie la fenêtre dans le presse papier (Alt + Impr écran) l'image est bien coupée.

N'est-il pas possible d'obtenir la taille exacte de la fenêtre ?
0
Herve_be Messages postés 1017 Date d'inscription mercredi 4 août 2010 Statut Membre Dernière intervention 25 avril 2024 2
18 sept. 2019 à 12:37
Bon, j'ai trouvé tout seul en regardant les autres fonctions de http://www.thescarms.com/VBasic/capture.aspx
Dans Capture the entire form il calcule la largeur comme ceci
Frm.ScaleX(Frm.Width, vbTwips, vbPixels)
et dans Capture the client area of the form
Frm.ScaleX(Frm.ScaleWidth, .ScaleMode, vbPixels)
donc j'ai fait
WidthForm = Frm.ScaleX(Frm.Width, vbTwips, vbPixels)
WidthClient = Frm.ScaleX(Frm.ScaleWidth, .ScaleMode, vbPixels)
Marge = (WidthForm - WidthClient) / 2
SavePicture CaptureWindow(Frm.hwnd, False, Marge, 0, Frm.ScaleX(Frm.Width, vbTwips, vbPixels) - 2 * Marge, Frm.ScaleY(Frm.Height, vbTwips, vbPixels) - Marge), LocalFile
et c'est bon dans tous les cas.
0
Rejoignez-nous