事情是这样的,想使用线程间通信ChatGPT走一波
using System; using System.Runtime.InteropServices; using System.Threading; public class Program { // 定义常量,表示自定义消息 private const int WM_CUSTOM_MESSAGE = 0x0400; // 定义用于接收消息的消息循环 private static void MessageLoop() { while (true) { // 接收消息并处理 if (NativeMethods.PeekMessage(out NativeMethods.MSG msg, IntPtr.Zero, 0, 0, 1)) { // 处理消息 if (msg.message == WM_CUSTOM_MESSAGE) { Console.WriteLine("Received custom message!"); } else if (msg.message == NativeMethods.WM_QUIT) { break; } NativeMethods.TranslateMessage(ref msg); NativeMethods.DispatchMessage(ref msg); } Thread.Sleep(100); // 等待一段时间,防止CPU占用过高 } } public static void Main() { // 创建一个新线程,并执行消息循环 Thread thread = new Thread(MessageLoop); thread.Start(); // 在主线程中发送消息 int threadId = thread.ManagedThreadId; NativeMethods.PostThreadMessage(threadId, WM_CUSTOM_MESSAGE, IntPtr.Zero, IntPtr.Zero); // 等待一段时间,以便接收消息 Thread.Sleep(1000); // 退出消息循环 NativeMethods.PostThreadMessage(threadId, NativeMethods.WM_QUIT, IntPtr.Zero, IntPtr.Zero); // 等待线程结束 thread.Join(); } } public static class NativeMethods { // 定义Windows常量 public const int WM_QUIT = 0x0012; // 定义Windows消息结构 [StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam; public IntPtr lParam; public uint time; public POINT pt; } [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; } [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool PostThreadMessage(int threadId, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool PeekMessage(out MSG msg, IntPtr hwnd, uint filterMin, uint filterMax, uint remove); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool TranslateMessage(ref MSG msg); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr DispatchMessage(ref MSG msg); }
代码看上去非常棒。。。偶而。。。。运行结果不是想的那样。
细查PostThreadMessage 总是返回false.为啥?(ChatGPT一直各种PeekMessage,GetMessage顾左右而言它)
查了很多,突然有看别人使用window API
[DllImport("kernel32"), SuppressUnmanagedCodeSecurity] static extern int GetCurrentThreadId();
为什么需要WindowsApi呢,想想这是通过window的。。。使用它的id合理。不对呀?
thread.ManagedThreadId;
我给的是.net托管里的ID。
如此使用在 MessageLoop 线程中GetCurrentThreadId();再传给PoseThreadMessage... 结果差不多了。
讲白 就是张三不是張三,张三是张三。
标签:IntPtr,NativeMethods,CharSet,间通信,线程,张三是,msg,static,public From: https://www.cnblogs.com/stweily/p/17640988.html