forum.boolean.name

forum.boolean.name (http://forum.boolean.name/index.php)
-   Библиотеки (http://forum.boolean.name/forumdisplay.php?f=28)
-   -   Работа с буфером обмена. (http://forum.boolean.name/showthread.php?t=6234)

impersonalis 10.08.2008 03:36

Работа с буфером обмена.
 
В общем я взял и объединил имеющиеся функции, свой код и свои порты кода с васика в одну библиотеку.
Отдельное спасибо:
Arthur
SBJoker
<<jimon>>
Были использованы так же исходники:
1 http://www.blitzbasic.com/codearcs/c....php?code=1767
2 http://www.rusedu.info/Print.php?sid=347
Распространение - бесплатное. Ссылка на всех причастных обязательна.

impersonalis 10.08.2008 03:37

Ответ: Работа с буфером обмена.
 
Для работы необходимы деклы на следующие системные библиотеки:
Цитата:

.lib "user32.dll"
Api_CloseClipboard%():"CloseClipboard"
Api_EmptyClipboard%():"EmptyClipboard"
Api_GetClipboardData%(uFormat):"GetClipboardData"
Api_GetClipboardText$(format%):"GetClipboardData"
Api_IsClipboardFormatAvailable%(format):"IsClipboa rdFormatAvailable"
Api_OpenClipboard%(hwnd):"OpenClipboard"
Api_SetClipboardData%(uFormat,hData):"SetClipboard Data"
Api_SetClipboardText%(format%,txt$):"SetClipboardD ata"

.lib "Kernel32.dll"
Api_GlobalAlloc%(uFlags,dwBytes):"GlobalAlloc"
Api_GlobalLock%(hMem):"GlobalLock"
Api_GlobalUnlock%(hMem):"GlobalUnlock"
Api_RtlCopyMemory(Destination,Source*,Length):"Rtl MoveMemory"
Api_RtlMoveMemory(Destination*,Source,Length):"Rtl MoveMemory"
Api_GlobalSize%(hMem%):"GlobalSize"
Api_WideCharToMultiByte(uCodePage,dwFlags,pWideCha rStr*,cchWideChar,pMultiByteStr*,cchMultiByte,pDef aultChar$,pfUsedDefaultChar):"WideCharToMultiByte"

impersonalis 10.08.2008 03:38

Ответ: Работа с буфером обмена.
 
Код:

;about:

;http://www.blitzbasic.com/codearcs/codearcs.php?code=1767
;http://www.rusedu.info/Print.php?sid=347
;impersonalis (icq 11-999-51-51)

;=============================================
;decls:

;.lib "user32.dll"
;Api_CloseClipboard%():"CloseClipboard"
;Api_EmptyClipboard%():"EmptyClipboard"
;Api_GetClipboardData%(uFormat):"GetClipboardData"
;Api_GetClipboardText$(format%):"GetClipboardData"
;Api_IsClipboardFormatAvailable%(format):"IsClipboardFormatAvailable"
;Api_OpenClipboard%(hwnd):"OpenClipboard"
;Api_SetClipboardData%(uFormat,hData):"SetClipboardData"
;Api_SetClipboardText%(format%,txt$):"SetClipboardData"

;.lib "Kernel32.dll"
;Api_GlobalAlloc%(uFlags,dwBytes):"GlobalAlloc"
;Api_GlobalLock%(hMem):"GlobalLock"
;Api_GlobalUnlock%(hMem):"GlobalUnlock"
;Api_RtlCopyMemory(Destination,Source*,Length):"RtlMoveMemory"
;Api_RtlMoveMemory(Destination*,Source,Length):"RtlMoveMemory"
;Api_GlobalSize%(hMem%):"GlobalSize"
;Api_WideCharToMultiByte(uCodePage,dwFlags,pWideCharStr*,cchWideChar,pMultiByteStr*,cchMultiByte,pDefaultChar$,pfUsedDefaultChar):"WideCharToMultiByte"

;=============================================
;DataFormats:

Const CBL_CF_TEXT = 1
;Const CBL_CF_BITMAP = 2
;Const CBL_CF_METAFILEPICT = 3
;Const CBL_CF_SYLK = 4
;Const CBL_CF_DIF = 5
;Const CBL_CF_TIFF = 6
;Const CBL_CF_OEMTEXT = 7
Const CBL_CF_DIB = 8
;Const CBL_CF_PALETTE = 9
;Const CBL_CF_PENDATA = 10
;Const CBL_CF_RIFF = 11
;Const CBL_CF_WAVE = 12
;Const CBL_CF_UNICODETEXT = 13
;Const CBL_CF_ENHMETAFILE = 14
Const CBL_CF_HDROP = 15
;Const CBL_CF_LOCALE = 16
;Const CBL_CF_MAX = 17
Const CBL_CF_X3 = -1;error

Dim CBL_OBJECTS_LIST$(0)

Function CBL_GetDataFormat%()
        Local BufferFormat%
        If Api_IsClipboardFormatAvailable(CBL_CF_TEXT)=True
                BufferFormat%=CBL_CF_TEXT
        ElseIf Api_IsClipboardFormatAvailable(CBL_CF_DIB)=True
                BufferFormat%=CBL_CF_DIB
        ;............... for another formats...............
        ElseIf Api_IsClipboardFormatAvailable(CBL_CF_HDROP)=True
                BufferFormat%=CBL_CF_HDROP
        Else
                BufferFormat%=CBL_CF_X3
        EndIf
        Return BufferFormat
End Function

Function CBL_GetData$(Format%)
        Local ObjectStr$=""
        Select Format
                Case CBL_CF_TEXT
                        Api_OpenClipboard(SystemProperty("AppHWND"))
                        ObjectStr=Api_GetClipboardText(Format)
                        Api_CloseClipboard()
                Case CBL_CF_DIB
                        ObjectStr=CBL_PasteImageFromClipboard()
                Case CBL_CF_HDROP
                        ObjectStr=CBL_PasteFilesFromClipboard%()
                ;............... for another formats...............
                Default
                        RuntimeError "CBL_GetData$(Format%)"
        End Select
       
        Return ObjectStr
End Function

Function CBL_SetData(Format,OS$)
        Select Format
                Case CBL_CF_TEXT
                        Api_OpenClipboard(SystemProperty("AppHWND"))
                        Api_EmptyClipboard()
                        Api_SetClipboardText(CBL_CF_TEXT,OS)
                        Api_CloseClipboard()
                Case CBL_CF_DIB
                        CBL_CopyImageToClipboard(Int(OS))
                ;............... for another formats...............
                Default
                        RuntimeError "CBL_SetData(Format,OS$)"
        End Select
End Function

Function CBL_PasteFilesFromClipboard%()
        ;port and mod  by impersonalis (from http://www.rusedu.info/print.php?sid=347)
        ;icq 11-999-51-51
       

        Api_OpenClipboard(SystemProperty("AppHWND"))
        Local lHandle% = Api_GetClipboardData(CBL_CF_HDROP)
       
        If lHandle>0
                Local lpResults% = Api_GlobalLock(lHandle)
                Local lBufferSize% =Api_GlobalSize(lpResults)
                Local FBuf=CreateBank(lBufferSize+1)

                Api_RtlMoveMemory(FBuf,lpResults,lBufferSize)
               
                Api_GlobalUnlock(lHandle)
                Api_CloseClipboard()
               
                Local fWide%=PeekInt(FBuf,16)

                Local FNbuf=CreateBank(lBufferSize-19)
                CopyBank Fbuf,20,FNbuf,0,lBufferSize-19
                FreeBank FBuf
               
                Local FNbufFormat=CreateBank(Floor(BankSize(FNbuf)/2)+1)

                If fWide=1
                        Api_WideCharToMultiByte(0,0,FNbuf,BankSize(FNbuf),FNbufFormat,BankSize(FNbufFormat),0,0)
                Else
                        CopyBank FNbuf,0,FNbufFormat,0,BankSize(FNbufFormat)
                EndIf
               
                FreeBank FNbuf
               
                Local COUNT=0
                Local EOS=False
                For i=0 To BankSize(FNbufFormat)-1
                        If PeekByte(FNbufFormat,i)<32
                                If Not EOS
                                        EOS=True
                                        COUNT=COUNT+1
                                EndIf
                        Else
                                EOS=False
                        EndIf
                Next
               
                Dim CBL_OBJECTS_LIST(COUNT)
                CBL_OBJECTS_LIST(0)=Str(COUNT)
               
                COUNT=0
                For i=0 To BankSize(FNbufFormat)-1
                        If PeekByte(FNbufFormat,i)>=32
                                CBL_OBJECTS_LIST(COUNT+1)=CBL_OBJECTS_LIST(COUNT+1)+Chr(PeekByte(FNbufFormat,i))
                        Else
                                COUNT=COUNT+1
                                If COUNT>Int(CBL_OBJECTS_LIST(0))
                                        Exit
                                EndIf
                        EndIf
                Next
               
                FreeBank FNbufFormat
       
                Return True
        EndIf
       
        Api_CloseClipboard()
        Return False

End Function

Function CBL_PasteImageFromClipboard()
        ;Paste the clipboard to a new Blitz3D image
        ;From "Copying a DIB to the clipboard", by John Simmons
        ;(http://www.codeproject.com)

        Local hDIB,himage,pbmi,btmp,sizeInfo,sizePal,width,height,bpp
        Local sizeBits,sizeDIB,x,y,offset,index,bytespp

        ;receive the bitmap from the clipboard as a DIB
        If Api_OpenClipboard(0) ;hwnd
                hDIB=Api_GetClipboardData(8) ;CF_DIB=8
                Api_CloseClipboard()
        EndIf

        If Not hDIB ;if we didn't get a DIB, return a dummy image
                himage=CreateImage(1,1)
                Return himage
        EndIf

        pbmi=Api_GlobalLock(hDIB) ;lock memory and get pointer to it

        btmp=CreateBank(40) ;initialize bank, we will resize it later

        Api_RtlMoveMemory(btmp,pbmi,40) ;move info header to bank
        sizeInfo=PeekInt(btmp,0) ;biSize

        ;calculate palette, Clipboard DIBs use the BITMAPINFO struct
        sizePal=PeekInt(btmp,32) ;biClrUsed
        If Not sizePal
                If PeekShort(btmp,14)<16 ;no color table for 16/24/32
                        sizePal=1 Shl PeekShort(btmp,14) ;biBitCount, colors=2/16/256
                Else
                        sizePal=PeekInt(btmp,16) ;biCompression, 16/32 use BI_BITFIELDS=3
                EndIf
        EndIf
        sizePal=sizePal*4 ;sizeof(RGBQUAD)

        width=PeekInt(btmp,4) ;biWidth
        height=PeekInt(btmp,8) ;biHeight
        bpp=PeekShort(btmp,14) ;biBitCount
        bytespp=bpp/8 ;bytes per pixel

        ;calculate bits, DWORD-aligned scanline (Width * BitCount) * Height
        sizeBits=((width*bpp+31)/32*4)*height
        sizeDIB=sizeInfo+sizePal+sizeBits ;total size

        ResizeBank btmp,sizeDIB ;resize bank to store DIB
        Api_RtlMoveMemory(btmp,pbmi,sizeDIB) ;move DIB to bank

        Api_GlobalUnlock(hDIB) ;unlock the DIB

        himage=CreateImage(width,height) ;new image to write

        ;calculate DWORD-aligned offset of bits for proper alignment
        ;we'll use biSize to store each pixel, we don't need it any more
        LockBuffer(ImageBuffer(himage))
        For y=0 To height-1
                offset=((width*bpp+31)/32*4)*y+sizeInfo+sizePal ;start of next scanline
                For x=0 To width-1
                        If bpp=1
                                index=PeekByte(btmp,offset+(x/8)) ;1-bit, looks nasty but it works
                                ;work out the bit, invert it, bitmask the byte and convert to 0/1
                                index=(index And (1 Shl (7-(x Mod 8)))) Shr (7-(x Mod 8))
                        EndIf
                        If bpp=4
                                index=PeekByte(btmp,offset+(x/2)) ;4-bit, work out the nibble
                                If x Mod 2 Then index=index And 15 ;get bits 0-3
                                If Not x Mod 2 Then index=index Shr 4 ;get bits 4-7
                        EndIf
                        If bpp=8
                                index=PeekByte(btmp,offset+x) ;8-bit, we have our index
                        EndIf
                        If bpp=24 Or bpp=32 ;get rgb offset
                                PokeByte btmp,0,PeekByte(btmp,offset+(x*bytespp)) ;blue
                                PokeByte btmp,1,PeekByte(btmp,offset+(x*bytespp)+1) ;green
                                PokeByte btmp,2,PeekByte(btmp,offset+(x*bytespp)+2) ;red
                        ElseIf bpp=16 ;rgb=565
                                PokeByte btmp,0,(PeekShort(btmp,offset+(x*bytespp)) And 31) Shl 3 ;blue
                                PokeByte btmp,1,((PeekShort(btmp,offset+(x*bytespp)) And 2016) Shr 5) Shl 2 ;green
                                PokeByte btmp,2,((PeekShort(btmp,offset+(x*bytespp)) And 63488) Shr 11) Shl 3 ;red
                        Else ;get palette index, 1/4/8-bit
                                    PokeByte btmp,0,PeekInt(btmp,sizeInfo+(index*4))
                                PokeByte btmp,1,PeekInt(btmp,sizeInfo+(index*4)+1)
                                PokeByte btmp,2,PeekInt(btmp,sizeInfo+(index*4)+2)
                          EndIf
                          WritePixelFast x,height-1-y,PeekInt(btmp,0),ImageBuffer(himage) ;biSize
                Next
        Next
        UnlockBuffer(ImageBuffer(himage))

        FreeBank btmp
        Return himage ;image handle

End Function

Function CBL_CopyImageToClipboard(himage)
        ;Copy a given Blitz3D image to the clipboard
        ;From "Copying a DIB to the clipboard", by John Simmons
        ;(http://www.codeproject.com)

        Local width,height,sizeBits,sizeInfo,sizeDIB,btmp,x,y,offset,hDIB,pbmi

        width=ImageWidth(himage)
        height=ImageHeight(himage)

        ;calculate bits, DWORD-aligned scanline (Width * BitCount) * Height
        sizeBits=((width*24+31)/32*4)*height
        sizeInfo=40 ;sizeof(BITMAPINFOHEADER)
        sizeDIB=sizeInfo+sizeBits ;total size

        btmp=CreateBank(sizeDIB) ;bank to store DIB

        ;calculate DWORD-aligned offset of bits for proper alignment
        ;we'll use biSize to store each pixel, we can fill it in after
        LockBuffer(ImageBuffer(himage))
        For y=0 To height-1
                offset=((width*24+31)/32*4)*y+sizeInfo ;start of next scanline
                For x=0 To width-1
                        PokeInt btmp,0,ReadPixelFast(x,height-1-y,ImageBuffer(himage)) ;biSize
                        PokeByte btmp,offset+(x*3),PeekByte(btmp,0) ;blue
                        PokeByte btmp,offset+(x*3)+1,PeekByte(btmp,1) ;green
                        PokeByte btmp,offset+(x*3)+2,PeekByte(btmp,2) ;red
                Next
        Next
        UnlockBuffer(ImageBuffer(himage))

        ;fill in the info header for our 24-bit DIB
        PokeInt btmp,0,sizeInfo ;biSize
        PokeInt btmp,4,width ;biWidth
        PokeInt btmp,8,height ;biHeight
        PokeShort btmp,12,1 ;biPlanes, must be 1
        PokeShort btmp,14,24 ;biBitCount
        PokeInt btmp,16,0 ;biCompression, RGB=0/RLE8=1/RLE4=2/BITFIELDS=3
        PokeInt btmp,20,sizeBits ;biSizeImage, zeros here mean "default"
        PokeInt btmp,24,0 ;biXPelsPerMeter
        PokeInt btmp,28,0 ;biYPelsPerMeter
        PokeInt btmp,32,0 ;biClrUsed
        PokeInt btmp,36,0 ;biClrImportant

        ;alloc memory block to store our DIB
        hDIB=Api_GlobalAlloc(66,sizeDIB) ;GHND=66, MOVEABLE=2|ZEROINIT=64

        If Not hDIB ;major bummer if we couldn't get memory block
                FreeBank btmp
                Return False ;fail code
        EndIf

        pbmi=Api_GlobalLock(hDIB) ;lock memory and get pointer to it

        Api_RtlCopyMemory(pbmi,btmp,sizeDIB) ;copy DIB to memory

        Api_GlobalUnlock(hDIB) ;unlock the DIB

        ;send the DIB to the clipboard
        If Api_OpenClipboard(0) ;hwnd
                Api_EmptyClipboard() ;free last data
                Api_SetClipboardData(8,hDIB) ;CF_DIB=8, hdata[bitmap]
                Api_CloseClipboard()
        EndIf

        FreeBank btmp
        Return True ;success code

End Function


impersonalis 10.08.2008 03:46

Ответ: Работа с буфером обмена.
 
Функции:
Function CBL_GetDataFormat%()
возвращает формат данных в буфере обмена (пока определены CBL_CF_TEXT,CBL_CF_DIB и CBL_CF_HDROP)

Function CBL_GetData$(Format%)
возвращает данные указанного типа (если это возможно) из буфера обмена.
для CBL_CF_TEXT: строку с текстом
для CBL_CF_DIB: дескриптор новой blitz image сохранённой в строке
для CBL_CF_HDROP: 1 - в случае успеха извлечения имён,и 0 - в противном. Если возвращена истина, то: CBL_OBJECTS_LIST(0) содержит кол-во скопированных файлов, а CBL_OBJECTS_LIST(1..n) - имена файлов.

Function CBL_SetData(Format,OS$)
Копирует в буфер информацию OS формата Format:
для CBL_CF_TEXT OS содержит текст
для CBL_CF_DIB OS содержит дескриптор копируемой blitz image
для CBL_CF_HDROP - пока не реализовано

impersonalis 10.08.2008 03:48

Ответ: Работа с буфером обмена.
 
Примеры:
вставка картинки в буфер
Код:

img=LoadImage("F:\11.png")
CBL_SetData(CBL_CF_DIB,Str(img))

вывод адресов скопированных файлов
Код:

BF%=CBL_GetDataFormat%()
CBL_GetData(BF)
For i=1 To CBL_OBJECTS_LIST(0)
        Print i+") "+CBL_OBJECTS_LIST(i)
Next


Reizel 18.08.2010 12:44

Ответ: Работа с буфером обмена.
 
Const CBL_CF_X3 = -1;error
Ах, русский народ :)

impersonalis 01.08.2011 01:31

Ответ: Работа с буфером обмена.
 
В 7-ке не работает

upd: но, что более вероятно, я создал *.decl-файл, вместо *.decls.
Что это вообще за нах? Расширение в 5 букв, а чо не в 10? Вчера в срочном порядке пришлось костыли прикручивать.


upd2: тем не менее, вставка текста в буфер обмена крешится


Часовой пояс GMT +4, время: 13:07.

vBulletin® Version 3.6.5.
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Перевод: zCarot