本文介绍了在带有 WM_COPYDATA 消息的结构中使用 LPCTSTR 是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个结构:

typedef struct tagCOPY_PACKET
{
    TCHAR szFile[_MAX_PATH];
    GUID guidSignature;

} S_COPY_PACKET;

我准备像这样用 WM_COPYDATA 发送数据:

I prepare to send data with WM_COPYDATA like this:

CString strFile = GetFileToOpenFromFileExplorerPath();

S_COPY_PACKET sCopyDataPacket;
_tcscpy_s(sCopyDataPacket.szFile, _MAX_PATH, strFile);
sCopyDataPacket.guidSignature = CopyData_Signature;
COPYDATASTRUCT cds;
cds.dwData = COPYDATA_TYPE_MSA;
cds.cbData = sizeof(sCopyDataPacket);
cds.lpData = &sCopyDataPacket;

DWORD_PTR dwResult;
if (SendMessageTimeout(hOtherInstance, WM_COPYDATA,
                NULL, (LPARAM)(LPVOID)&cds, SMTO_BLOCK, 2000, &dwResult) != 0)
{
}

另一端:

BOOL CMeetingScheduleAssistantDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
    if (pCopyDataStruct->dwData == COPYDATA_TYPE_MSA)
    {
        S_COPY_PACKET* pCopyPacket = (S_COPY_PACKET*)(pCopyDataStruct->lpData);
        if (pCopyPacket->guidSignature != CopyData_Signature)
        {
            // Bad GUID
            return FALSE;
        }

        if (GetLastActivePopup() != this) // Popup windows!
        {
            // TODO: Tell user?
            return FALSE;
        }

        theApp.SetFileToOpenFromFileExplorer(pCopyPacket->szFile);

        OpenFileFromFileExplorer();

        return TRUE;
    }

    return FALSE;
}

它工作正常.我只是想知道像这样改变我的结构是否可以接受:

It works fine. I just wanted to know if it would be acceptable to change my structure like this:

typedef struct tagCOPY_PACKET
{
    LPCTSTR lpszFile;
    GUID guidSignature;

} S_COPY_PACKET;

然后使用:

S_COPY_PACKET sCopyDataPacket;
sCopyDataPacket.lpszFile = strFile.GetBufferSetLength(_MAX_PATH);
sCopyDataPacket.guidSignature = CopyData_Signature;
COPYDATASTRUCT cds;
cds.dwData = COPYDATA_TYPE_MSA;
cds.cbData = sizeof(sCopyDataPacket);
cds.lpData = &sCopyDataPacket;
...

并且,一旦消息被发布和处理:

And, once the message has been posted and processed:

strFile.ReleaseBuffer();

LPCTSTR 方法与 WM_COPYDATA 一起使用是否安全,如果是,为什么?

Is it safe to use the LPCTSTR approach with WM_COPYDATA and if so, why?

推荐答案

WM_COPYDATA 的文档说:

传递的数据不得包含指向接收数据的应用程序无法访问的对象的指针或其他引用.

因此,当 CMeetingScheduleAssistantDlg 位于不同的可执行文件中时,您无法传递 LPCTSTR 值.如果它在同一个可执行文件中,那么它很可能有效.

Therefore, when CMeetingScheduleAssistantDlg lives in a different executable, you cannot pass an LPCTSTR value. If it is in the same executable, chances are that it works.

这篇关于在带有 WM_COPYDATA 消息的结构中使用 LPCTSTR 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:45