一、背景
QT 与 GO之间进行通信,可以很方便在windows平台下用golang开发后台服务,c++负责UI界面
二、效果图
在这里插入图片描述

三、QT 程序接收方
重写nativeEvent函数

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    if (eventType == "windows_generic_MSG") //windows平台
    {      
        MSG* msg = reinterpret_cast<MSG*>(message);
        if (msg->message == WM_COPYDATA)
        {
            COPYDATASTRUCT *data = reinterpret_cast<COPYDATASTRUCT*>(msg->lParam);
            DWORD count = data->cbData;
            char *pData = new char[count];
            memset(pData, 0, count);
            wcstombs(pData, (wchar_t*)(data->lpData), count);
            QString str = pData;
            qDebug()<<str;
            return true;//消息不再进行传递,不再处理
        }
    }

    return QWidget::nativeEvent(eventType, message, result);
}

四、go程序发送方

package main

import (
	"fmt"
	"github.com/lxn/win"
	"syscall"
	"unsafe"
)

type COPYDATASTRUCT struct {
	dwData uintptr
	cbData uint32
	lpData uintptr
}

func main()  {

	var windowStr string = "ChatTest"
	var classStr = "TXGuiFoundation"
	lpClassName, _ := syscall.UTF16PtrFromString(classStr)
	lpWindowName,_ := syscall.UTF16PtrFromString(windowStr)

	_ = lpClassName
	hWnd := win.FindWindow(nil, lpWindowName)

	if hWnd == 0 {
		fmt.Println("没有找到窗口句柄")
	}else{
		fmt.Println("找到窗口句柄: %v", hWnd)
	}
	
	var data = "apple vs huawei"
	arrUtf16, _ := syscall.UTF16FromString(data)

	pCopyData := new(COPYDATASTRUCT)
	pCopyData.dwData = 0
	pCopyData.cbData = uint32(len(arrUtf16)*2 + 1)
	pCopyData.lpData = uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(data)))
	win.SendMessage(hWnd, win.WM_COPYDATA, 0, uintptr(unsafe.Pointer(pCopyData)))
}