简体   繁体   English

如何将字符数组复制到剪贴板?

[英]How do I copy a character array to the clipboard?

I am trying to get my application to copy a character array to the clipboard so it can be pasted into an IE address bar. 我正在尝试让我的应用程序将字符数组复制到剪贴板,以便可以将其粘贴到IE地址栏中。 I am having an issue with getting this working. 我在使用此功能时遇到问题。 This is the code I am working with: 这是我正在使用的代码:

HGLOBAL glob = GlobalAlloc(GMEM_FIXED,32);
memcpy(glob,array,sizeof(array));
OpenClipboard(hDlg);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT,glob);
CloseClipboard();

Array is declared as: 数组声明为:

char array[500];

This will cause the program to crash. 这将导致程序崩溃。 However if I switch out sizeof(array) with a number it ok but The only 8 characters are copyied to the clipboard. 但是,如果我用数字切换出sizeof(array) ,但是只有8个字符被复制到剪贴板。

Can anyone advise me on how to solve this issue? 谁能建议我如何解决这个问题? I am targeting the Win32 API directly, not using MFC. 我直接针对Win32 API,而不使用MFC。

You are only allocating 32 bytes of global memory: 您只分配32个字节的全局内存:

GlobalAlloc(GMEM_FIXED,32);

...and then trying to cram 500 bytes in to a 32 byte bag: ...然后尝试将500字节塞进32字节的包中:

memcpy(glob,array,sizeof(array));

Change the GlobalAlloc to: 将GlobalAlloc更改为:

GlobalAlloc(GMEM_FIXED,sizeof(array));

Further, you are pasting the data as Unicode text ( CF_UNICODETEXT ), but it's not Unicode text. 此外,您将数据粘贴为Unicode文本( CF_UNICODETEXT ),但不是Unicode文本。 I would imagine that would cause... problems. 我想那会导致...问题。

Paste it as plain text instead: 将其粘贴为纯文本:

SetClipboardData(CF_TEXT,glob);

You are copying 500 chars ( sizeof(array) ) into a buffer that only has space for 32 chars. 您正在将500个字符( sizeof(array) )复制到一个只有32个字符的空间的缓冲区中。 All the remaining chars trample over random data and cause the crash. 所有剩余的字符践踏随机数据并导致崩溃。

I created a function to save and load clipboard. 我创建了一个保存和加载剪贴板的功能。

#include <Windows.h>
char* LoadClipboard()
{
    static HANDLE clip;
    if(OpenClipboard(NULL))
    {
        clip = GetClipboardData(CF_TEXT);
        CloseClipboard();
    }
    return (char*) clip;
}

void SaveClipboard(char* text)
{
    HGLOBAL global = GlobalAlloc(GMEM_FIXED,strlen(text) + 1); //text size + \0 character
    memcpy(global,text,strlen(text));  //text size + \0 character
    if(OpenClipboard(NULL))
    {
        EmptyClipboard();
        SetClipboardData(CF_TEXT,global);
        CloseClipboard();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM