1. 程式人生 > >使用WindowsAPI取剪貼簿文字

使用WindowsAPI取剪貼簿文字

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
	HGLOBAL hGlobal;
	PCHAR pText;
	PCHAR pGlobal;

	OpenClipboard(GetDesktopWindow()); // Open the clipboard

	hGlobal = GetClipboardData(CF_TEXT);
	if (hGlobal == FALSE) // is equal "NULL" condition
		cout << "No text in the clipboard!\n";
	else
	{
		// Allocation memory 
		pText = new char[GlobalSize(hGlobal) + 1];

		// lock and get the clipboard text address.
		pGlobal = (char*)GlobalLock(hGlobal);
		strcpy(pText,pGlobal); // copy string

		GlobalUnlock(hGlobal); // Unlock
		CloseClipboard(); // Close the clipboard

		cout << "Text in the Clipboard: " << pText << endl;
	}
	cin.ignore();
	return 0;
}

// Unicode version
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<windows.h>
#include<locale.h>
using namespace std;
int main()
{
	HGLOBAL hGlobal;
	static wchar_t* pText;
	wchar_t* pGlobal;

	OpenClipboard(GetDesktopWindow()); // Open the clipboard

	hGlobal = GetClipboardData(CF_UNICODETEXT);
	if (hGlobal == FALSE) // is equal "NULL" condition
		cout << "No text in the clipboard!\n";
	else
	{
		// Allocation memory 
		pText = new wchar_t[(GlobalSize(hGlobal) + 1) * sizeof(wchar_t)];

		// lock and get the clipboard text address.
		pGlobal = (wchar_t*)GlobalLock(hGlobal);

		lstrcpy(pText,pGlobal); // copy string

		GlobalUnlock(hGlobal); // Unlock
		CloseClipboard(); // Close the clipboard

		setlocale(LC_ALL, "chs");
		wcout << pText << endl;
		
	}
	if (pText){
		delete[]pText;
		pText = NULL;
	}
		
	cin.ignore();
	return 0;
}