1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "ClipboardHelper.h"
17 #include <string>
18 #include <windows.h>
19 #include "StringHelper.h"
20 using namespace std;
21
SetClipboardData(const std::string & data)22 void ClipboardHelper::SetClipboardData(const std::string& data)
23 {
24 string newData = StringHelper::Utf8ToString(data);
25 OpenClipboard(NULL);
26 EmptyClipboard();
27 HANDLE hHandle = GlobalAlloc(GMEM_FIXED, newData.size() + 1);
28 char* pData = (char*)GlobalLock(hHandle);
29 copy(newData.begin(), newData.end(), pData);
30 ::SetClipboardData(CF_TEXT, hHandle);
31 GlobalUnlock(hHandle);
32 CloseClipboard();
33 }
34
GetClipboardData()35 const std::string ClipboardHelper::GetClipboardData()
36 {
37 string data;
38 if (!IsClipboardFormatAvailable(CF_TEXT)) {
39 return data;
40 }
41 OpenClipboard(NULL);
42 HANDLE h = ::GetClipboardData(CF_TEXT);
43 char* p = (char*)GlobalLock(h);
44 string str(p);
45 data = str;
46 GlobalUnlock(h);
47 CloseClipboard();
48 StringHelper::Encode encode = StringHelper::DetectEncode((uint8_t*)str.c_str(), str.size());
49 if (encode == StringHelper::Encode::ANSI) {
50 data = StringHelper::StringToUtf8(data);
51 }
52 return data;
53 }