Windows clipboard is shared place for exchanging data between applications. An application can read data from clipboard as well as it can set the data to it. Data can be in the form of plain text, rich formatted text, HTML or any other OLE object format. A good example of clipboard data exhange 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 clipboard for reading or modification. 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

  • If the function succeeds, the return value is nonzero.
  • If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

OpenClipboard fails if another window has the clipboard open. An application should call the CloseClipboard function after every successful call to OpenClipboard. The window identified by the hWndNewOwner parameter does not become the clipboard owner unless the EmptyClipboard function is called. If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; 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);

Parameters

    uFormat - Specifies a clipboard format. For a description of the standard clipboard formats, see Standard Clipboard Formats.

Return Values

If the function succeeds, the return value is the handle of a clipboard object in the specified format. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

SetClipboardData

The SetClipboardData function places data on the clipboard in a specified clipboard format. The window must be the current clipboard owner, and the application must have called the OpenClipboard function. (When responding to the WM_RENDERFORMAT and WM_RENDERALLFORMATS messages, the clipboard owner must not call OpenClipboard before calling SetClipboardData.)
HANDLE SetClipboardData(
  UINT uFormat, /* clipboard format */
  HANDLE hMem   /* data handle */
);

Parameters

  • uFormat - Specifies a clipboard format. This parameter can be a registered format or any of the standard clipboard formats. For more information, see 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.
After SetClipboardData is called, the system owns the object identified by the hMem parameter. The application can read the data, but must not free the handle or leave it locked. If the hMem parameter identifies a memory object, the object must have been allocated using the GlobalAlloc function with the GMEM_MOVEABLE and GMEM_DDESHARE flags.

EmptyClipboard function

Empties the clipboard and frees handles to data in the clipboard. The function then assigns ownership of the clipboard to the window that currently has the clipboard open.

Syntax

BOOL WINAPI EmptyClipboard(void);

Parameters

This function has no parameters.

Return value

Type: BOOL If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before calling EmptyClipboard, an application must open the clipboard by using the OpenClipboard function. If the application specifies a NULL window handle when opening the clipboard, EmptyClipboard succeeds but sets the clipboard owner to NULL. Note that this causes SetClipboardData to fail.

CloseClipboard function

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

Syntax

BOOL WINAPI CloseClipboard(void);

Parameters

This function has no parameters.

Return value

Type: BOOL If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows 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 ...

#