"Windows Programming" series Nineth: Clipboard usage

Source: Internet
Author: User

We learned about common common dialog boxes in this article to understand the use of the Clipboard, which is often used for copy-and-paste functions.

The Clipboard is the first feature that Windows joins, and since it's very practical, we use it almost every day. With the Clipboard, we can pass data from one application to another, which is a simple interprocess communication.

Many document processing software has copy, cut, paste function, these are implemented with the Windows clipboard, of course, we can also implement their own clipboard function in our program, this article we will implement their own clipboard. When using the Clipboard, the source data is first uploaded to the Clipboard and then transferred from the Clipboard to the destination when needed, so it seems that we are moving directly from the source to the destination.

Windows controls, such as EditBox, have been copied, cut, and pasted inside the control, so we can use them directly. However, many of our controls do not have this function, such as static text control, the window created by ourselves, etc., we have no way to copy and paste directly, these are required by our own implementation. Or the usual, let's start with the Clipboard function, and then use the example to demonstrate the basic usage.

    • Clipboard common functions

Whether copying or pasting, use the Clipboard to open it first, open the Clipboard API function as follows:

BOOL OpenClipboard (HWND hwndnewowner);

The unique parameter, Hwndnewowner, is the window handle associated with the Clipboard, and if the parameter is NULL, it is associated to the current task.

Before you can set data from the source to the Clipboard, you must empty the Clipboard and get possession of the Clipboard. The API functions are as follows:

Bool EmptyClipboard (void)

The function has no arguments.

Set the data to the Clipboard, which is the copy operation:

HANDLE SetClipboardData (UINT uformat, HANDLE hmem);

The parameter Uformat represents the format of the data to be transferred to the Clipboard, there are more than 10 predefined formats, we list several of the most commonly used, and others refer to MSDN:

Cf_text: Indicates the format to be set as a null-terminated ANSI string, and a string labeled C. This is the simplest scrapbook data format.

Cf_unicodetext: The format is a string containing the Unicode character set.

Cf_bitmap: The format is a device-dependent bitmap.

Parameter hmem: Sets the handle to the data, typically the handle returned by the GlobalAlloc function.

After you set up the data or get the data from the Clipboard, you need to close the Clipboard, or else the Clipboard will no longer be open by other applications. The API functions are:

Bool closeclipboard (void);

The function has no arguments.

To get data from the Clipboard, which is the paste operation, the API functions are:

HANDLE GetClipboardData (UINT uformat);

The parameter uformat is the data format you want to get.

Query the clipboard for data in the specified format:

BOOL isclipboardformatavailable (UINT format);

The parameter format is the one you want to query, and the function does not need to open the Clipboard.

    • Clipboard instance

These are some of the most important clipboard-related functions:

Below we use these functions to complete the basic text copy and paste and image copy and paste function, in order to demonstrate, we set a picture and a line of text as a data source, while creating two buttons "copy image" and "Copy text" for copying images and text, respectively, when clicked to copy the data.

For the sake of simplicity, I used the mouse left lifted as a paste trigger, the location of the paste is lifted mouse position, you can click in different places to lift the mouse after repeated paste, the specific code is as follows:

#include  <windows.h> #include  <tchar.h> #define  IDC_LABEL      1000#define idc_copy_img  1001#define idc_copy_txt  1002static tchar  szappname[] = text ("Clipboard demo");static lresult callback wndproc  (Hwnd, uint, wparam, lparam); Int winapi winmain (hinstance hinstance,  Hinstance hprevinstance, pstr szcmdline, int icmdshow) {      hwnd     hwnd;     msg       msg;     wndclass wndclass;     wndclass.style          = CS_HREDRAW | CS_VREDRAW;      wndclass.lpfnWndProc   = WndProc;      wndclass.cbclsextra    = 0;     wndclass.cbWndExtra    = 0;      wndclass.hInstance     = hInstance;      Wndclass.hicon         = loadicon (NULL, IDI_APPLICATION );      wndclass.hcursor       = loadcursor ( Null, idc_arrow);     wndclass.hbrbackground =  (HBRUSH)   Getstockobject (White_brush);     wndclass.lpszmenuname  = null;      wndclass.lpszClassName = szAppName;     if  (! RegisterClass (&wndclass))      {           MessageBox  (Null, text ("this program requires windows nt!"),  Szappname, mb_iconerror);           return 0;     }           hwnd = createwindow (szAppName,             // window class name                            szAppName,            // window caption                           WS_OVERLAPPEDWINDOW,   window style                           CW_USEDEFAULT,        // initial x position                           CW_USEDEFAULT,        // initial y position                           400,               // initial x  size                           300,               // initial y size                            null,             // parent window handle                            NULL,              // window menu handle                            hinstance,        // program instance handle                            null);             // creation parameters           ShowWindow (hwnd, icmdshow);       updatewindow (hWnd);          while  ( GetMessage (&msg, null, 0, 0))      {           translatemessage (&msg);           dispatchmessage (&msg);      }     return  msg.wparam;} Static int drawbmp (hdc hdc, int xdst, int ydst, int width,  Int height, int bytesperpixel, unsigned char *ppixels) {int ret =  -1; hdc hdcmem; bitmapinfo bmi; Byte *pbits = null;memset (&bmi, 0x00, sizeof (bitmapinfo)); bmi.bmiHeader.biSize  = sizeof (bitmapinfoheader); bmi.bmiheader.biwidth = width;bmi.bmiheader.biheight =  height;bmi.bmiheader.biplanes = 1;bmi.bmiheader.bibitcount = bytesperpixel*8;bmi.bmiheader.bicompression = bi_rgb;hdcmem = createcompatibledc (HDC );if  (Hdcmem) {hbitmap hbitmap = createdibsection (null, &bmi, dib_rgb_colors,   (void **) &pbits, null, 0);if  (HBITMAP) {hgdiobj holdbmp =  SelectObject (Hdcmem, hbitmap); memcpy (pbits, ppixels, width * height *  Bytesperpixel); BitBlt (hdc, xdst, ydst, width, height, hdcmem, 0, 0, srccopy); SelectObject (hdcmem, holdbmp);D eleteobject (HBITMAP); ret = 0;} DeleteDC (HDCMEM);} Return ret;} Static lresult callback wndproc (Hwnd hwnd, uint message, wparam wparam ,  lparam lparam) {Hdc hdc;static hbitmap hbmp;static bitmap  bm;switch   (message) {Case wm_create:createwindow (TEXT ("STATIC"),  text ("Hello, world!"),  ws_child| Ws_visible, 10, 160, 100, 20, hwnd,  (HMENU) idc_label, null, null); CreateWindow (TEXT ("button"),  text ("Copy image"),  ws_child| ws_visible, 10, 190, 100, 20, hwnd,  (HMENU) idc_copy_img, null, null); CreateWindow (TEXT ("button"),  text ("Copy text"),  ws_child| ws_visible, 10, 220, 100, 20, hwnd,  (HMENU) idc_copy_txt, null, null); hbmp =  (HBITMAP) LoadImage (Null, text ("Start.bmp"),  image_bitmap, 0, 0, lr_ LoadFromFile); GetObject (Hbmp, sizeof (BITMAP), &NBSP;&AMP;BM); return 0;case wm_paint:{paintstruct ps;hdc  = beginpaint (HWND,&NBSP;&AMP;PS); Hdc hmemdc = createcompatibledc (HDC); hbitmap holdbitmap =  (HBITMAP) SelectObject (hmemdc, hbmp); BitBlt (hdc, 10, 10, bm.bmwidth, bm.bmheight, hmemdc, 0, 0, srccopy);D Eletedc (HMEMDC); EndPaint (hwnd, &PS);} Return 0;case wm_command:{int id = loword (WParam);switch  (ID) {Case IDC_COPY _img:{bool ret; byte *pdata = null; Bitmapinfo bmpinfo;bmpinfo.bmiheader.bisize = sizeof (Bitmapinfoheader); bmpinfo.bmiheader.biwidth = bm.bmwidth;bmpinfo.bmiheader.biheight = bm.bmheight; bmpinfo.bmiheader.biplanes = 1;bmpinfo.bmiheader.bibitcount = 32; bmpinfo.bmiheader.bicompression = bi_rgb; HDC&NBSP;HCLIENTDC&NBSP;=&NBSP;GETDC (HWND); Hdc hmemdc = createcompatibledc (HCLIENTDC); Hbitmap hbitmap = createdibsection (hmemdc, &bmpinfo, dib_rgb_colors,  (void  **) &pdata, null, 0); SelectObject (Hmemdc, hbitmap); Ret = bitblt (hmemdc, 0, 0, bm.bmwidth,  bm.bmheight, hclientdc, 10, 10, srccopy);D Eletedc (HMEMDC); long len = bm.bmwidth * bm.bmheight * 4; HGLObal hclipdata = globalalloc (Ghnd, len); byte *pclipdata =  (byte *) GlobalLock (hclipdata); memcpy (Pclipdata, pdata, len); Ret = globalunlock (Hclipdata); Ret = openclipboard (hWnd); Ret = emptyclipboard (); SetClipboardData (Cf_bitmap, hclipdata), Ret = closeclipboard ();D eleteobject (HBITMAP); ReleaseDC (HWND,&NBSP;HCLIENTDC); MessageBox (Hwnd, text ("Image has been copy into clipboard"),  text ("info"), &NBSP;MB_OK);} break;case idc_copy_txt:{bool ret; tchar buf[256]; GetWindowText (GetDlgItem (Hwnd, idc_label),  buf, _countof (BUF)); Int len = _tcslen (BUF)  + 1; Hglobal hclipdata = globalalloc (ghnd, len * sizeof (TCHAR)); tchar *pclipdata =  (tchar *) GlobalLock (hclipdata); memcpy (Pclipdata, buf, len  * sizeof (TCHAR));p clipdata[len-1] =  (TCHAR) 0;ret =&nbsP GlobalUnlock (Hclipdata); Ret = openclipboard (hWnd); Ret = emptyclipboard (); SetClipboardData (Cf_text, hclipdata); Ret = closeclipboard (); MessageBox (Hwnd, text ("Text has been copy into clipboard"),  text ("info"), &NBSP;MB_OK);} Break;default:break;}} return 0;case wm_lbuttonup:{bool ret; Word xpos = loword (LParam);  word ypos = hiword (LParam);ret =  Isclipboardformatavailable (Cf_bitmap);if  (ret) {ret = openclipboard (hWnd); Hglobal hglb = getclipboarddata (Cf_bitmap);//len = globalsize (HGLB); byte *pclipdata =  (byte *) GlobalLock (HGLB); HDC&NBSP;HCLIENTDC&NBSP;=&NBSP;GETDC (hWnd);D rawbmp (hclientdc, xpos, ypos, bm.bmwidth,  Bm.bmheight, 4, pclipdata); GlobalUnlock (HGLB); CloseClipboard (); ReleaseDC (HWND,&NBSP;HCLIENTDC);} Ret = isclipboardformatavailable (Cf_text);if  (ret) {RET&NBSp;= openclipboard (HWND); Hglobal hglb = getclipboarddata (CF_TEXT); tchar *pclipdata =  (tchar *) GlobalLock (HGLB); HDC&NBSP;HCLIENTDC&NBSP;=&NBSP;GETDC (hWnd); Int len = _tcslen (Pclipdata);//len =  GlobalSize (HGLB); TextOut (Hclientdc, xpos, ypos, pclipdata, len); GlobalUnlock (HGLB); CloseClipboard (); ReleaseDC (HWND,&NBSP;HCLIENTDC);}} Return 0;case wm_destroy:deleteobject (hbmp); PostQuitMessage (0); return 0 ;} return defwindowproc  (Hwnd, message, wparam, lparam);}

In the example, when setting up the Clipboard, you need to use the GlobalAlloc function to allocate global memory, to set up and get the data before you need to GlobalLock function lock memory general copy data, and then use the GlobalUnlock function to unlock memory, these functions are basically discussed using the Clipboard, Divert on the line, see MSDN for detailed parameters. After running the sample program, click on the copy image and copy the text of the random click, the effect is as follows:

In general, the basic application of the Clipboard is relatively simple, related to other or more information please see MSDN. Please leave a message for me if you have any doubts about this article.

More experience Exchange can join the Windows programming discussion QQ Group :454398517.


Focus on the public platform: The programmer Interaction Alliance (coder_online), you can get the first original technical articles, and (java/c/c++/android/windows/ Linux) Technology Daniel is a friend, online communication programming experience, get programming basics, solve programming problems. Programmer Interactive Alliance , Developer's own home.

Reprint Please specify the source http://www.coderonline.net/?p=1815 , thank you for your cooperation!

Windows Programming Series Nineth: Clipboard use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.