"Windows Programming" series Nineth: Clipboard usage

Source: Internet
Author: User

Tag: amp operation One net multiple tran IDC DCL Itme

??

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 adds, because it's useful and we almost always use it every day. With the Clipboard, we are able to pass data from one application to another, a simple interprocess communication.

Many document processing software have copy, cut, paste function, these are implemented with the Windows clipboard, of course, we can also implement their own clipboard function in our program. In this article we will implement our own clipboard. When using the Clipboard, the source data is first uploaded to the Clipboard. Transfer from the Clipboard to the destination when needed. So it looks like we're moving directly from the source to the destination.

Windows controls, such as EditBox, have implemented copy, cut, and paste functionality within the control, so we can use them directly. But we have very many controls that do not have this function. For example, a static text control, a form created by itself, and so on, we have no way to copy and paste directly, these are required by ourselves.

It's still the same ritual. Here we introduce the Clipboard often using functions, and then use the example to demonstrate the basic usage.

    • The Clipboard often uses functions

Whether copying or pasting, use the Clipboard to open it first, open the Clipboard API functions such as the following:

BOOL OpenClipboard (HWND hwndnewowner);

The unique number of Hwndnewowner is the form handle associated with the clipboard, assuming that the number is NULL, which is associated to the current task.

You must clear the Clipboard before you can set the data from the source to the Clipboard. Get possession of the Clipboard at the same time. API functions such as the following:

Bool EmptyClipboard (void)

The function does not have a number of parameters.

Sets the data to the Clipboard. That is, the copy operation:

HANDLE SetClipboardData (UINT uformat, HANDLE hmem);

The Uformat indicates that you want to set the data format to be transferred to the Clipboard, with more than 10 formats defined in advance. We have listed some of the most frequently used, others please refer to MSDN:

Cf_text: Represents 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 that includes 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 the data has been set or fetched from the Clipboard. You need to close the Clipboard, or other applications will no longer be able to open the Clipboard. The API functions are:

Bool closeclipboard (void);

The function does not have a number of parameters.

Gets the data from the Clipboard. That is, the paste operation, the API function is:

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 basic clipboard-related functions:

Below we use these functions to complete the main text copy and paste and image copy and paste function. For demonstration. We set up a picture and a line of text as the data source. At the same time, create two button "copy image" and "Copy text" respectively for copying images and text, copying the data for when clicked.

For the simplicity of the program. I used the mouse left lifted as a paste trigger, the location of the paste is raised mouse position, you can click in different places to lift the mouse to paste repeatedly, detailed code such as the following:

#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 W     INAPI 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_ic       ONERROR);   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,//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 (&AMP;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, &AMP;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, ten, (HMENU) Idc_label, NULL, and NULL); CreateWindow (Text ("button"), text ("Copy image"), ws_child| Ws_visible, ten, N, a, A, a, hWnd, (HMENU) idc_copy_img, NULL, NULL); CreateWindow (Text ("button"), text ("Copy text"), ws_child| Ws_visible, Max, (+), (HMENU) idc_copy_txt, NULL, NULL), hbmp = (hbitmap) loadimage (NULL, TEXT ("Start.bmp"), IM Age_bitmap, 0, 0, lr_loadfromfile); GetObject (hbmp, sizeof (BITMAP), &AMP;BM); return 0;case wm_paint:{paintstruct ps;hdc = BeginPaint (hWnd, &ps); HDC HMEMDC = CreateCompatibleDC (HDC); Hbitmap Holdbitmap = (hbitmap) SelectObject (HMEMDC, hbmp); BitBlt (HDC, ten, 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 hclientdc = 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, ten, srccopy);D Eletedc (HM EMDC); 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, HCLIENTDC); MessageBox (hWnd, text ("image has been copy to clipboard"), Text ("info"), 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 = GlobalUnlock (hclipdata); ret = OpenClipboard (hWnd); ret = EmptyClipboard (); SetClipboardData (Cf_text, hclipdata); ret = CloseClipboard (); MessageBox (hWnd, text ("text has been copy into Clipboard"), Text ("info"), 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 hclientdc = GetDC (hWnd);D rawbmp (HCLIENTDC, XPos, YPos, Bm.bmwidth, Bm.bmheight, 4, pclipdata); GlobalUnlock (HGLB); CloseClipboard (); ReleaseDC (HWnd, HCLIENTDC);} ret = isclipboardformatavailable (cf_text); if (ret) {ret = OpenClipboard (hWnd); Hglobal hglb = GetClipboardData (cf_text); TCHAR *pclipdata = (tchaR *) GlobalLock (HGLB); HDC hclientdc = GetDC (hWnd); int len = _tcslen (pclipdata);//len = GlobalSize (HGLB); TextOut (HCLIENTDC, XPos, YPos, Pclipdata, Len); GlobalUnlock (HGLB); CloseClipboard (); ReleaseDC (HWnd, HCLIENTDC);}} Return 0;case Wm_destroy:deleteobject (hbmp); PostQuitMessage (0); return 0;} Return DefWindowProc (hWnd, message, WParam, LParam);}

In the demo sample, when you set the Clipboard. Need to use GlobalAlloc function to allocate global memory, set up and get data before you need to GlobalLock function lock memory general copy data, and then use GlobalUnlock function to unlock memory, these functions in the use of the Clipboard basically became a discussion, divert can, To learn more about the specific number of references, see MSDN.

This demo sample program executes, click on the copy image and copy the text of the arbitrary click, the effect such as the following:

In general, the basic application of the Clipboard is still relatively simple. See MSDN for other or a number of other related information.

Please leave a message for me if you have any doubts about this article.

Many other experience exchanges can increase the Windows programming discussion QQ Group :454398517.


focus on the public platform: Program Ape Interactive Alliance (coder_online), you can first get original technical articles, and (Java/c/c++/android/windows/linux) technology Daniel Friends, online communication programming experience, get programming basics, solve programming problems. Program Ape 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 usage

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.