Home > C++, VC++, Windows API > Function for copying text to clipboard!

Function for copying text to clipboard!

A helper function for copying any given text to clipboard…

static bool CopyTextToClipboard( HWND hWindow_i,
			      LPCTSTR lpctszText_i )
{
    // Open clipboard
    if( !lpctszText_i || !::OpenClipboard( hWindow_i ))
    {
        return false;
    }

    // Clear clipboard
    EmptyClipboard();

    const int nTotalAllocLen = ( _tcslen( lpctszText_i ) + 1 )
			     * sizeof( TCHAR ) ;
    HGLOBAL hGlobal = GlobalAlloc( GMEM_MOVEABLE,
			        nTotalAllocLen );
    if( !hGlobal )
    {
        CloseClipboard();
        return false;
    }

    // Lock allocated buffer for copying
    LPTSTR lptszCopyStr = RCAST( LPTSTR, GlobalLock( hGlobal ));
    memcpy( lptszCopyStr, lpctszText_i, nTotalAllocLen );
    GlobalUnlock( hGlobal );
    ASSERT( GetLastError() == NO_ERROR );

    // Clipboard format
    UINT uClipBoardFormat = 0;
    #ifdef _UNICODE
        uClipBoardFormat = CF_UNICODETEXT;
    #else
        uClipBoardFormat = CF_TEXT;
    #endif

    // Set data to clipboard
    HANDLE hClip = SetClipboardData( uClipBoardFormat, hGlobal );
    CloseClipboard();

    // Return status
    return ( hClip ? true : false );
}// End CopyTextToClipboard
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: