Excel Hints

Page 1 of 2 1 2 LastLast
Results 1 to 20 of 23

Thread: Saving Clipboard data as picture

  1. #1

    Saving Clipboard data as picture

    ITT, How would you reference the clipboard's data when it is a picture (ie: you have copied a picture to the clipboard), and save it to a file?

    I have looked high and low for an answer and have yet to find one. I know you can do this in vb6 (that is the answer I keep finding) and I know you can do this for text, but there must be some way of doing this?

    Any help would be much appreciated.
    -Once my PC stopped working, so I kicked it......Then it started working again

  2. #2
    If the picture is a bitmap, you can access the clipboard as type CF_DIB which VBA can handle by calling a .wsc file. Other image formats are a bit more complicated.

    Could you post more specifics about what you are trying to accomplish?

    Stan

  3. #3
    Ideally I would want to do it in Access, but it is fine if it is in another office app.

    I want to create a macro that will save the contents of the clipboard (if a picture, especially if someone has pressed "printscreen") to a jpg, bmp or png file to a location on their computer. I would prefer a straight save to the location rather than pasting it to word or paint and saving it (i did see one sort of solution using sendkeys and timing events, but that wouldn't be suitable).

    Thanks for your reply. Hope what I am looking for is clearer to you.
    -Once my PC stopped working, so I kicked it......Then it started working again

  4. #4
    Moderator VBAX Master Tommy's Avatar
    Joined
    May 2004
    Location
    Houston, TX
    Posts
    1,140
    Location
    I found this at this location. I have not tested and don't have access to test it with.

    http://groups.google.ca/group/micros...rnum=2&safe=on

    [VBA]
    Option Compare Database
    Option Explicit

    Private Declare Function apiDeleteObject Lib "gdi32" _
    Alias "DeleteObject" (ByVal hObject As Long) As Long

    Private Sub cmdCreateIPicture_Click()
    ' *********************
    ' You must set a Reference to:
    ' "OLE Automation"
    ' for this function to work.
    ' Goto the Menu and select
    ' Tools->References
    ' Scroll down to:
    ' Ole Automation
    ' and click in the check box to select
    ' this reference.

    Dim lngRet As Long
    Dim lngBytes As Long
    Dim hPix As IPicture
    Dim hBitmap As Long
    'Dim hPicBox As StdPicture

    Me.OLEBound19.SetFocus
    'Me.OLEbound19.SizeMode = acOLESizeZoom
    DoCmd.RunCommand acCmdCopy
    hBitmap = GetClipBoard
    Set hPix = BitmapToPicture(hBitmap)
    SavePicture hPix, "C:\ole.bmp"
    apiDeleteObject (hBitmap)
    Me.Image0.Picture = "C:\ole.bmp"

    Set hPix = Nothing
    End Sub

    ' Here's the code behind the code module

    Option Compare Database
    Option Explicit

    Private Const vbPicTypeBitmap = 1

    Private Type IID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
    End Type

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

    Private Declare Function OleCreatePictureIndirect Lib _
    "olepro32.dll" _
    (PicDesc As PictDesc, RefIID As IID, _
    ByVal fPictureOwnsHandle As Long, _
    IPic As IPicture) As Long

    '''Windows API Function Declarations

    'Does the clipboard contain a bitmap/metafile?
    Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal
    wFormat As Integer) As Long

    'Open the clipboard to read
    Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long)
    As Long

    'Get a pointer to the bitmap/metafile
    Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As
    Integer) As Long

    'Close the clipboard
    Private Declare Function CloseClipboard Lib "user32" () As Long

    'Create our own copy of the metafile, so it doesn't get wiped out by
    subsequent clipboard updates.
    Declare Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA"
    (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long

    'Create our own copy of the bitmap, so it doesn't get wiped out by
    subsequent clipboard updates.
    Declare Function CopyImage Lib "user32" (ByVal handle As Long, ByVal un1
    As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long

    'The API format types we're interested in
    Const CF_BITMAP = 2
    Const CF_PALETTE = 9
    Const CF_ENHMETAFILE = 14
    Const IMAGE_BITMAP = 0
    Const LR_COPYRETURNORG = &H4
    ' Addded by SL Apr/2000
    Const xlPicture = CF_BITMAP
    Const xlBitmap = CF_BITMAP

    '*******************************************
    'DEVELOPED AND TESTED UNDER MICROSOFT ACCESS 97 VBA ONLY
    '
    'Copyright: Lebans Holdings 1999 Ltd.
    ' May not be resold in whole or part. Please feel
    ' free to use any/all of this code within your
    ' own application without cost or obligation.
    ' Please include the one line Copyright notice
    ' if you use this function in your own code.
    '
    'Name: BitmapToPicture &
    ' GetClipBoard
    '
    'Purpose: Provides a method to save the contents of a
    ' Bound or Unbound OLE Control to a Disk file.
    ' This version only handles BITMAP files.
    ' '
    'Author: Stephen Lebans
    'Email: Step...@lebans.com
    'Web Site: www.lebans.com
    'Date: Apr 10, 2000, 05:31:18 AM
    '
    'Called by: Any
    '
    'Inputs: Needs a Handle to a Bitmap.
    ' This must be a 24 bit bitmap for this release.
    '
    'Credits:
    'As noted directly in Source :-)
    '
    'BUGS:
    'To keep it simple this version only works with Bitmap files of
    16 or 24 bits.
    'I'll go back and add the
    'code to allow any depth bitmaps and add support for
    'metafiles as well.
    'No serious bugs notices at this point in time.
    'Please report any bugs to my email address.
    '
    'What's Missing:
    '
    '
    'HOW TO USE:
    '
    '*******************************************

    Public Function BitmapToPicture(ByVal hBmp As Long, _
    Optional ByVal hPal As Long = 0&) _
    As IPicture '

    ' The following code is adapted from
    ' Bruce McKinney's "Hardcore Visual Basic"
    ' And Code samples from:
    ' http://www.mvps.org/vbnet/code/bitma...screenole.htmv
    ' and examples posted on MSDN

    ' The handle to the Bitmap created by CreateDibSection
    ' cannot be passed directly as the PICTDESC.Bitmap element
    ' that get's passed to OleCreatePictureIndirect.
    ' We need to create a regular bitmap from our CreateDibSection
    'Dim hBmptemp As Long, hBmpOrig As Long
    'Dim hDCtemp As Long

    'Fill picture description
    Dim lngRet As Long
    Dim IPic As IPicture, picdes As PictDesc, iidIPicture As IID

    'hDCtemp = apiCreateCompatibleDC(0)
    'hBmptemp = apiCreateCompatibleBitmap _
    '(mhDCImage, lpBmih.bmiHeader.biWidth, _
    'lpBmih.bmiHeader.biHeight)

    'hBmpOrig = apiSelectObject(hDCtemp, hBmptemp)

    ' lngRet = apiBitBlt(hDCtemp, 0&, 0&, lpBmih.bmiHeader.biWidth, _
    ' lpBmih.bmiHeader.biHeight, mhDCImage, 0, 0, SRCCOPY)

    'hBmptemp = apiSelectObject(hDCtemp, hBmpOrig)
    'Call apiDeleteDC(hDCtemp)

    picdes.Size = Len(picdes)
    picdes.Type = vbPicTypeBitmap
    picdes.hBmp = hBmp

    ' No palette info here
    ' Everything is 24bit for now

    picdes.hPal = hPal
    ' ' Fill in magic IPicture GUID
    {7BF80980-BF32-101A-8BBB-00AA00300CAB}
    iidIPicture.Data1 = &H7BF80980
    iidIPicture.Data2 = &HBF32
    iidIPicture.Data3 = &H101A
    iidIPicture.Data4(0) = &H8B
    iidIPicture.Data4(1) = &HBB
    iidIPicture.Data4(2) = &H0
    iidIPicture.Data4(3) = &HAA
    iidIPicture.Data4(4) = &H0
    iidIPicture.Data4(5) = &H30
    iidIPicture.Data4(6) = &HC
    iidIPicture.Data4(7) = &HAB
    '' Create picture from bitmap handle
    lngRet = OleCreatePictureIndirect(picdes, iidIPicture, True, IPic)
    '' Result will be valid Picture or Nothing-either way set it
    Set BitmapToPicture = IPic
    End Function

    Function GetClipBoard() As Long
    ' Adapted from original Source Code by:
    '* MODULE NAME: Paste Picture
    '* AUTHOR & DATE: STEPHEN BULLEN, Business Modelling Solutions Ltd.
    '* 15 November 1998
    '*
    '* CONTACT: Step...@BMSLtd.co.uk
    '* WEB SITE: http://www.BMSLtd.co.uk

    ' Handles for graphic Objects
    Dim hClipBoard As Long
    Dim hBitmap As Long
    Dim hBitmap2 As Long

    'Check if the clipboard contains the required format
    'hPicAvail = IsClipboardFormatAvailable(lPicType)

    ' Open the ClipBoard
    hClipBoard = OpenClipboard(0&)

    If hClipBoard <> 0 Then
    ' Get a handle to the Bitmap
    hBitmap = GetClipboardData(CF_BITMAP)

    If hBitmap = 0 Then GoTo exit_error
    ' Create our own copy of the image on the clipboard, in the
    appropriate format.
    'If lPicType = CF_BITMAP Then
    hBitmap2 = CopyImage(hBitmap, IMAGE_BITMAP, 0, 0,
    LR_COPYRETURNORG)
    ' Else
    ' hBitmap2 = CopyEnhMetaFile(hBitmap, vbNullString)
    ' End If

    'Release the clipboard to other programs
    hClipBoard = CloseClipboard

    GetClipBoard = hBitmap2
    Exit Function

    End If

    exit_error:
    ' Return False
    GetClipBoard = -1
    End Function


    [/VBA]

  5. #5
    Doesn't quite work, seems to want to copy an ole object all the time.

    Plus it fills up the clipboard, so copy and paste no longer work "out of memory".

    Thanks for the effort though, is almost there
    -Once my PC stopped working, so I kicked it......Then it started working again

  6. #6
    The original coding in this file was from Stephen Bullen. He used a form with a picture object on it. The picture object was filled with the data on the clipboard. Anyway, I've written a routine that uses his functions to deal with a picture on the clipboard. The routine will allow you to select the destination where you want to save your picture (bmp file) and you may choose your name. If no picturedata is present, you will be informed.

    Just press printscreen, select the workbook with this routine and run the routine save_a_picture.

    Hope you'll like this one.

    Charlize

  7. #7
    That is perfect Charlize. Thank you very much.
    (sorry for the late reply, been too busy with other projects to test it
    -Once my PC stopped working, so I kicked it......Then it started working again

  8. #8
    You're a rock star, mate. That's just what I needed. Thanks for posting that!

  9. #9

  10. #10
    Quote Originally Posted by Charlize
    The original coding in this file was from Stephen Bullen. He used a form with a picture object on it. The picture object was filled with the data on the clipboard. Anyway, I've written a routine that uses his functions to deal with a picture on the clipboard. The routine will allow you to select the destination where you want to save your picture (bmp file) and you may choose your name. If no picturedata is present, you will be informed.

    Just press printscreen, select the workbook with this routine and run the routine save_a_picture.

    Hope you'll like this one.

    Charlize
    New to this board so I may have not replied correctly.

    Please email me a copy of your modified code bit as I'm trying to do the same thing or if there is a way to do this in Excel 2010, let me know. Thanks,

  11. #11
    Quote Originally Posted by doctorcpu
    New to this board so I may have not replied correctly.

    Please email me a copy of your modified code bit as I'm trying to do the same thing or if there is a way to do this in Excel 2010, let me know. Thanks,
    Just download the zip from a few posts above. Tried it in excel 2010 and works as described (at least for me).

    Charlize

  12. #12
    Thanks for the reply, I was trying to get this to run in Excel 2010 64BIT.

  13. #13
    Quote Originally Posted by Charlize
    Just download the zip from a few posts above. Tried it in excel 2010 and works as described (at least for me).

    Charlize
    Looking for the zip file that you are referencing. If you can repost it I would be very appreciative. Thank you.

  14. #14
    As requested the zip with excel file.

    Charlize
    Attached Files Attached Files
      To view attachments your post count must be 0 or greater. Your post count is 0 momentarily.

  15. #15
    Stephen's code will not work in 64bit Office as it is. I do not have 64bit installed to test, but I believe it should convert as follows:
    [vba]

    '************************************************************************** *
    '*
    '* MODULE NAME: Paste Picture
    '* AUTHOR & DATE: STEPHEN BULLEN, Office Automation Ltd
    '* 15 November 1998
    '*
    '* CONTACT: Stephen@oaltd.co.uk
    '* WEB SITE: http://www.oaltd.co.uk
    '*
    '* DESCRIPTION: Creates a standard Picture object from whatever is on the clipboard.
    '* This object can then be assigned to (for example) and Image control
    '* on a userform. The PastePicture function takes an optional argument of
    '* the picture type - xlBitmap or xlPicture.
    '*
    '* The code requires a reference to the "OLE Automation" type library
    '*
    '* The code in this module has been derived from a number of sources
    '* discovered on MSDN.
    '*
    '* To use it, just copy this module into your project, then you can use:
    '* Set Image1.Picture = PastePicture(xlPicture)
    '* to paste a picture of whatever is on the clipboard into a standard image control.
    '*
    '* PROCEDURES:
    '* PastePicture The entry point for the routine
    '* CreatePicture Private function to convert a bitmap or metafile handle to an OLE reference
    '* fnOLEError Get the error text for an OLE error code
    '************************************************************************** *

    Option Explicit
    Option Compare Text

    ''' User-Defined Types for API Calls

    'Declare a UDT to store a GUID for the IPicture OLE Interface
    Private Type GUID
    Data1 As Long
    Data2 As Long
    Data3 As Long
    Data4(0 To 7) As Byte
    End Type

    'Declare a UDT to store the bitmap information
    Private Type uPicDesc
    Size As Long
    Type As Long
    hPic As LongPtr
    hPal As LongPtr
    End Type

    '''Windows API Function Declarations

    'Does the clipboard contain a bitmap/metafile?
    Private Declare PtrSafe Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Long) As Long

    'Open the clipboard to read
    Private Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As Long

    'Get a pointer to the bitmap/metafile
    Private Declare PtrSafe Function GetClipboardData Lib "user32" (ByVal wFormat As Long) As LongPtr

    'Close the clipboard
    Private Declare PtrSafe Function CloseClipboard Lib "user32" () As Long

    'Convert the handle into an OLE IPicture interface.
    Private Declare PtrSafe Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As LongPtr, IPic As IPicture) As Long

    'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
    Declare PtrSafe Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As LongPtr, ByVal lpszFile As String) As LongPtr

    'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
    Declare PtrSafe Function CopyImage Lib "user32" (ByVal handle As LongPtr, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As LongPtr

    'The API format types we're interested in
    Const CF_BITMAP = 2
    Const CF_PALETTE = 9
    Const CF_ENHMETAFILE = 14
    Const IMAGE_BITMAP = 0
    Const LR_COPYRETURNORG = &H4

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''
    ''' Subroutine: PastePicture
    '''
    ''' Purpose: Get a Picture object showing whatever's on the clipboard.
    '''
    ''' Arguments: lXlPicType - The type of picture to create. Can be one of:
    ''' xlPicture to create a metafile (default)
    ''' xlBitmap to create a bitmap
    '''
    ''' Date Developer Action
    ''' --------------------------------------------------------------------------
    ''' 30 Oct 98 Stephen Bullen Created
    ''' 15 Nov 98 Stephen Bullen Updated to create our own copies of the clipboard images
    '''

    Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture

    'Some pointers
    Dim h As Long, hPicAvail As Long, hPtr As LongPtr, hPal As LongPtr, lPicType As Long, hCopy As LongPtr

    'Convert the type of picture requested from the xl constant to the API constant
    lPicType = IIf(lXlPicType = xlBitmap, CF_BITMAP, CF_ENHMETAFILE)

    'Check if the clipboard contains the required format
    hPicAvail = IsClipboardFormatAvailable(lPicType)

    If hPicAvail <> 0 Then
    'Get access to the clipboard
    h = OpenClipboard(0&)

    If h > 0 Then
    'Get a handle to the image data
    hPtr = GetClipboardData(lPicType)

    'Create our own copy of the image on the clipboard, in the appropriate format.
    If lPicType = CF_BITMAP Then
    hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
    Else
    hCopy = CopyEnhMetaFile(hPtr, vbNullString)
    End If

    'Release the clipboard to other programs
    h = CloseClipboard

    'If we got a handle to the image, convert it into a Picture object and return it
    If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, lPicType)
    End If
    End If

    End Function


    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''
    ''' Subroutine: CreatePicture
    '''
    ''' Purpose: Converts a image (and palette) handle into a Picture object.
    '''
    ''' Requires a reference to the "OLE Automation" type library
    '''
    ''' Arguments: None
    '''
    ''' Date Developer Action
    ''' --------------------------------------------------------------------------
    ''' 30 Oct 98 Stephen Bullen Created
    '''

    Private Function CreatePicture(ByVal hPic As LongPtr, ByVal hPal As LongPtr, ByVal lPicType) As IPicture

    ' IPicture requires a reference to "OLE Automation"
    Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture

    'OLE Picture types
    Const PICTYPE_BITMAP = 1
    Const PICTYPE_ENHMETAFILE = 4

    ' Create the Interface GUID (for the IPicture interface)
    With IID_IDispatch
    .Data1 = &H7BF80980
    .Data2 = &HBF32
    .Data3 = &H101A
    .Data4(0) = &H8B
    .Data4(1) = &HBB
    .Data4(2) = &H0
    .Data4(3) = &HAA
    .Data4(4) = &H0
    .Data4(5) = &H30
    .Data4(6) = &HC
    .Data4(7) = &HAB
    End With

    ' Fill uPicInfo with necessary parts.
    With uPicInfo
    .Size = Len(uPicInfo) ' Length of structure.
    .Type = IIf(lPicType = CF_BITMAP, PICTYPE_BITMAP, PICTYPE_ENHMETAFILE) ' Type of Picture
    .hPic = hPic ' Handle to image.
    .hPal = IIf(lPicType = CF_BITMAP, hPal, 0) ' Handle to palette (if bitmap).
    End With

    ' Create the Picture object.
    r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)

    ' If an error occured, show the description
    If r <> 0 Then Debug.Print "Create Picture: " & fnOLEError(r)

    ' Return the new Picture object.
    Set CreatePicture = IPic

    End Function

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''
    ''' Subroutine: fnOLEError
    '''
    ''' Purpose: Gets the message text for standard OLE errors
    '''
    ''' Arguments: None
    '''
    ''' Date Developer Action
    ''' --------------------------------------------------------------------------
    ''' 30 Oct 98 Stephen Bullen Created
    '''

    Private Function fnOLEError(lErrNum As Long) As String

    'OLECreatePictureIndirect return values
    Const E_ABORT = &H80004004
    Const E_ACCESSDENIED = &H80070005
    Const E_FAIL = &H80004005
    Const E_HANDLE = &H80070006
    Const E_INVALIDARG = &H80070057
    Const E_NOINTERFACE = &H80004002
    Const E_NOTIMPL = &H80004001
    Const E_OUTOFMEMORY = &H8007000E
    Const E_POINTER = &H80004003
    Const E_UNEXPECTED = &H8000FFFF
    Const S_OK = &H0

    Select Case lErrNum
    Case E_ABORT
    fnOLEError = " Aborted"
    Case E_ACCESSDENIED
    fnOLEError = " Access Denied"
    Case E_FAIL
    fnOLEError = " General Failure"
    Case E_HANDLE
    fnOLEError = " Bad/Missing Handle"
    Case E_INVALIDARG
    fnOLEError = " Invalid Argument"
    Case E_NOINTERFACE
    fnOLEError = " No Interface"
    Case E_NOTIMPL
    fnOLEError = " Not Implemented"
    Case E_OUTOFMEMORY
    fnOLEError = " Out of Memory"
    Case E_POINTER
    fnOLEError = " Invalid Pointer"
    Case E_UNEXPECTED
    fnOLEError = " Unknown Error"
    Case S_OK
    fnOLEError = " Success!"
    End Select

    End Function
    [/vba]
    Be as you wish to seem

  16. #16

    Out Of Memory Error

    Hello, i tried the above code but i still received the "Out Of Memory" Error

  17. #17

    MS Access

    I'm Sorry I tried the Code in MS Access, now i see that your Attached Code is for Excel,

    Do you have a code that can be used in access, the other i tried and i'm getting the "Out Of memory" Error

  18. #18
    Hi yoelyfie,
    after experimenting with the code and running into errors, I kept receiving "Out of Memory" messages on normal Copy&Paste actions in the editor. It helped to call CloseClipboard to properly close the Clipboard.

  19. #19
    Many thanks, it's what I was looking for.

  20. #20

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •