dotnet发送端代码:
using System;
using System.Runtime.InteropServices;namespace mymsg
{public class MyMsg{public struct CopyDataStruct{public IntPtr dwData;public int cbData;[MarshalAs(UnmanagedType.LPStr)]public string lpData;}public const int WM_COPYDATA = 0x004A;//当一个应用程序传递数据给另一个应用程序时发送此消息指令//通过窗口的标题来查找窗口的句柄 [DllImport("User32.dll", EntryPoint = "FindWindow")]private static extern int FindWindow(string lpClassName, string lpWindowName);//在DLL库中的发送消息函数[DllImport("User32.dll", EntryPoint = "SendMessage")]private static extern int SendMessage(int hWnd, // 目标窗口的句柄 int Msg, // 在这里是WM_COPYDATAint wParam, // 第一个消息参数ref CopyDataStruct lParam // 第二个消息参数);public static int findW(string title){return FindWindow(null, title);}public static void send_title(string title, string text){CopyDataStruct cds;cds.dwData = (IntPtr)1; //这里可以传入一些自定义的数据,但只能是4字节整数 cds.lpData = text; //消息字符串cds.cbData = System.Text.Encoding.GetEncoding("utf-8").GetBytes(text).Length + 1;//注意,这里的长度是按字节来算的SendMessage(FindWindow(null, title), WM_COPYDATA, 0, ref cds);}public static void send_handle(int hwnd, string text){CopyDataStruct cds;cds.dwData = (IntPtr)1; //这里可以传入一些自定义的数据,但只能是4字节整数 cds.lpData = text; //消息字符串cds.cbData = System.Text.Encoding.GetEncoding("utf-8").GetBytes(text).Length + 1;//注意,这里的长度是按字节来算的SendMessage(hwnd, WM_COPYDATA, 0, ref cds);}}
}
pyqt接收端代码
import win32con
class COPYDATASTRUCT(ctypes.Structure):_fields_ = [('dwData', ctypes.wintypes.LPARAM),('cbData', ctypes.wintypes.DWORD),('lpData', ctypes.c_void_p)]
PCOPYDATASTRUCT = ctypes.POINTER(COPYDATASTRUCT)
class MainW(PyQt5.QtWidgets.QMainWindow):def nativeEvent(self, event_type, message):r = super().nativeEvent(event_type, message)if sys.platform == "linux":return rif event_type == "windows_generic_MSG":msg = ctypes.wintypes.MSG.from_address(message.__int__())if msg.message == win32con.WM_COPYDATA:p_cds = ctypes.cast(msg.lParam, PCOPYDATASTRUCT)s = ctypes.string_at(p_cds.contents.lpData).decode("gbk")#处理消息数据if s == "end":self.refresh_grid1()else:try:self.sql_cmd(s)except TypeError as e:logging.info(e)return r