What is Windows Clipboard?

Windows clipboard is a shared software module for exchanging data between two or more applications. An application can retrieve user data from the clipboard as well as it can store the new data. Data can be in the form of plain ASCII text, UNICODE text, rich formatted text, HTML or any other OLE object format. Apart from Windows clipboard, all modern GUI based operating systems like Mac, Linux, Android etc have a clipboard component in their operating system.

A good example of clipboard text exchange is opening notepad and office word and type some text, select it and copy with CTRL+C and press CTRL+V on office word. We see the same text appeared in word. Now we can type some other text in word and select it and do the same to copy that text to notepad. The data is copied to windows clipboard in one application and again readback from clipboard to other application. CRTL+C and CTRL+V are shortcut keys however applications use Windows Clipboard functions to do these backend process.

We are writing a small demonstration application to show the utility of basic clipboard functions. Clipboard can supports many type of data formats. However to make our demo application simple we will mostly deal with plain text format. Before we start we are listing all clipboard functions and discussing their utilities.

OpenClipboard function

Opens the Windows clipboard for reading or modification and sametime this prevents other applications from modifying the clipboard content.

Syntax

BOOL WINAPI OpenClipboard(HWND hWndNewOwner);

Parameters

  • hWndNewOwner - A handle to the window to be associated with the open clipboard. If this parameter is NULL, the open clipboard is associated with the current task.

Return value

  • A bool value of TRUE or nonzero is returned on success.
  • A bool value of FALSE or zero is returned on failures. Extended error information can be retrieved via a call to GetLastError.

Remarks

Only one application or window at one point of time can take the ownership of the clipboard. Thus OpenClipboard() might fail when another window has the clipboard open and not closed. An application should call the CloseClipboard function and close the session which was opened earlier with OpenClipboard. A call to EmptyClipboard function is necessary to become the owner of the clipboard. The window identified by the hWndNewOwner parameter should be valid to take ownership of the clipboard. If an application calls OpenClipboard with hWndNewOwner as NULL, EmptyClipboard will set the owner to NULL and this causes SetClipboardData to fail.

GetClipboardData

The GetClipboardData function retrieves data from the clipboard in a specified format. The clipboard must have been opened previously.

HANDLE GetClipboardData(UINT uFormat);

Arguments

    UINT uFormat: A numeric value in the form of C/C++ macro specifies the format of the clipboard data. See "Clipboard Formats".

Return Values

  • A successful call returns the handle of a clipboard object in the specified format.
  • A NULL (zero) handle is returned in the failure cases and call GetLastError for getting extended error informations.

Clipboard Formats

Clipboard functions uses a formatting parameter for treating the data field in the clipboard. Clipboard can hold data in UNICODE or rich edit text format however the same data can be read as pain text format. Thus clipboard APIs can do data and text conversions on the fly. These are some data formats -

  • Text formats - CF_TEXT, CF_UNICODETEXT, CF_OEMTEXT.
  • Bitmap images - CF_BITMAP, CF_DIB, CF_DIBV5.
  • Metafile images - CF_ENHMETAFILE, CF_METAFILEPICT.

SetClipboardData

The SetClipboardData function places data on the clipboard in a specified clipboard format. Application should open clipboard with OpenClipboard function and take the ownership using the top window handle.

HANDLE SetClipboardData (
  UINT uFormat, /* clipboard format */
  HANDLE hMem   /* data handle */
);

Arguments

  • uFormat - Specifies a clipboard data format. See "Clipboard Formats". This parameter can be a registered format or any of the standard clipboard formats. For more information on MSDN for Registered Clipboard Formats and Standard Clipboard Formats.
  • hMem - Handle to the data in the specified format. This parameter can be NULL, indicating that the window provides data in the specified clipboard format (renders the format) upon request. If a window delays rendering, it must process the WM_RENDERFORMAT and WM_RENDERALLFORMATS messages.

Remarks

After SetClipboardData is called by the application, the system owns the object identified by the hMem parameter. Now the application can read the data but should not free the handle or leave it locked. This data is owned in system's shared space and can be read by other applications. A subsequent call to EmptyClipboard() by other application frees the data and makes the clipboard empty. GlobalAlloc function with the GMEM_MOVEABLE and GMEM_DDESHARE flags should be used to allocate memory objects.

EmptyClipboard function

Empties the clipboard and frees data handle of the existing data in the clipboard. The function then assigns ownership of the clipboard to the window that currently has the clipboard open. This should be called before calling SetClipboardData().

Syntax

BOOL WINAPI EmptyClipboard(void);

Arguments

This function has no parameters.

Return output

A bool value of TRUE or nonzero is returned on the success of this function. A bool value of FALSE or zero is returned on failures and a call to GetLastError() gives the extended error information.

Remarks

An application should open the clipboard by calling the OpenClipboard() function before calling EmptyClipboard(). If the application specifies a NULL as the window handle parameter when opening the clipboard, EmptyClipboard succeeds but sets the clipboard owner to NULL. SetClipboardData will fail in case clipboard ownership is null.

CloseClipboard function

CloseClipboard Closes the clipboard provided it was opened with OpenClipboard earlier.

Syntax

BOOL WINAPI CloseClipboard(void);

Arguments

VOID - This function has no arguments.

Return output

A bool value of TRUE or nonzero is returned on the success of this function. A bool value of FALSE or zero is returned on failures and a call to GetLastError() gives the extended error information.

Remarks

An application / top window has finished retrieving or changing the clipboard, should close the clipboard by calling CloseClipboard() function. The session opened via OpenClipboard() closes by CloseClipboard() and thus this gives opportunity to other applications to access the clipboard.

Application example code

class CClipBoardDlg : public CDialog
{

public :
  CClipBoardDlg(CWnd* pParent = NULL);
  enum { IDD = IDD_CLIPBOARD_DIALOG };
  CString  m_szGetClipText;
  CString  m_szSetClipText;

protected :
  virtual void DoDataExchange(CDataExchange* pDX);

protected:

  virtual BOOL OnInitDialog();

  afx_msg void OnGetClipboardData();
  afx_msg void OnSetClipboardData();

  DECLARE_MESSAGE_MAP()
};

CClipBoardDlg::CClipBoardDlg(CWnd* pParent /*=NULL*/)
  : CDialog(CClipBoardDlg::IDD, pParent)
{

  m_szGetClipText = _T("");
  m_szSetClipText = _T("");
}

void CClipBoardDlg::DoDataExchange(CDataExchange* pDX)
{
  CDialog::DoDataExchange(pDX);
  DDX_Text(pDX, IDC_EDIT_GETCLIPBOARD, m_szGetClipText);
  DDX_Text(pDX, IDC_EDIT_SETCLIPBOARD, m_szSetClipText);
}

BEGIN_MESSAGE_MAP(CClipBoardDlg, CDialog)
  ON_COMMAND(IDC_GETCLIPBOARDDATA, OnGetClipboardData)
  ON_COMMAND(IDC_SETCLIPBOARDDATA, OnSetClipboardData)
END_MESSAGE_MAP()

/* CClipBoardDlg message handlers */

BOOL CClipBoardDlg::OnInitDialog()
{
  CDialog::OnInitDialog();

  return TRUE; 
}

/* GetClipboardData as text format (steps) */
void CClipBoardDlg::OnGetClipboardData() 
{
  if(OpenClipboard() == 0) {
    AfxMessageBox("Unable to open clipboard!");
    return;
  }

  /* Get handle of clipboard object for ANSI text */
  HANDLE hData = GetClipboardData(CF_TEXT);


  /* Lock the handle to get the actual text pointer */
  char * pszText = static_cast<char*>( GlobalLock(hData) );


  this->m_szGetClipText = pszText;
  UpdateData(FALSE);

  /* Release the lock */
  GlobalUnlock( hData );

  /* Release the clipboard */
  CloseClipboard();


}

/* SetClipboardData as text format (steps) */
void CClipBoardDlg::OnSetClipboardData() 
{
  int len ;
  HGLOBAL hMem;
  LPTSTR  lptstrCopy;
  if(OpenClipboard() == 0) {
    AfxMessageBox("Unable to open clipboard!");
    return;
  }

  UpdateData(TRUE);

  len = m_szSetClipText.GetLength();
  hMem =  GlobalAlloc(GMEM_MOVEABLE, len +1);
  lptstrCopy = (LPTSTR)GlobalLock(hMem);
  strcpy(lptstrCopy, (LPCTSTR) m_szSetClipText);
  GlobalUnlock(hMem);
  EmptyClipboard();
  /* Get handle of clipboard object for ANSI text */
  SetClipboardData(CF_TEXT, hMem);
  /* Release the clipboard */
  CloseClipboard();  
}

/* CClipBoardApp.h - Application Class header */
class CClipBoardApp : public CWinApp
{
public:
  CClipBoardApp();
  virtual BOOL InitInstance();

};

/* CClipBoardApp.cpp - Application Class implementation */

CClipBoardApp::CClipBoardApp()
{
}

/* The one and only CClipBoardApp object */

CClipBoardApp theApp;

/* CClipBoardApp initialization */

BOOL CClipBoardApp::InitInstance()
{
  AfxEnableControlContainer();

  /* Standard initialization */

  CClipBoardDlg dlg;
  m_pMainWnd = &dlg;
  int nResponse = dlg.DoModal();
  if (nResponse == IDOK)
  {
  }
  else if (nResponse == IDCANCEL)
  {
  }

  /* Since the dialog has been closed, return FALSE so that we exit the application, rather than start the application's message pump. */
  return FALSE;
}

Output

Get/SetClipboardData example demo application

About our authors: Team EQA

Further readings

Where is WinMain() function in MFC application ?

MFC hides WinMain in its framework and includes source file on WinMain(). This explains how framework calls global CWinApp::Initinstance() from entry WinMain.

What is the utility of CWinApp class?

This is constructed during global C++ objects are constructed and is already available when Windows calls the WinMain function, which is supplied by the ...

Basic steps in Win32 GUI Application with source code.

Define a custom Window class structure, Register the class name, CreateWindow, Show windows and write message get and dispatch loop statements. Define the Window CallBack procedure and write the handlers.

What is a Window CallBack procedure and what is its utility?

DispatchMessage() is a API which indirectly triggers the Window CallBack procedure. Message structure members from this function are passed to the CallBack procedure. CallBack procedure should implement event handlers depending on the need of the application.

What are LPARAM and WPARAM in window proc function?

LPARAM and WPARAM are the two parameters in Window CallBack procedure. They signifies parameters of various events. They are used in handing individual events.

What are the basic steps of a typical MFC based application?

We need to write WinMain and need to follow all these in a Win32 application. However we need not to write much if we are writing an application with MFC ...

#