做了一个关于消息传递的小程序,不知道为什么消息总是收不到呢?我把代码贴出来,麻烦大家给看看。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread SQL_Thread;
public struct tagMSG
{
public int hwnd;
public uint message;
public int wParam;
public long lParam;
public uint time;
public int pt;
}
public tagMSG msg;
public const int WM_CX_NULL = 0x400 + 100;
[DllImport("user32.dll")]
private static extern int PostThreadMessage(int threadId, uint msg, int wParam, int lParam);
[DllImport("user32.dll")]
private static extern int GetMessage(ref tagMSG lpMsg, int hwnd, int wMsgFilterMin, int wMsgFilterMax);
public void SQL_ThreadExectue()
{
//Thread.Sleep(50);
while (GetMessage(ref msg, 0, 0, 0) > 0)
{
if (msg.message == WM_CX_NULL)
{
MessageBox.Show("消息收到!");
}
}
}
private void button1_Click(object sender, EventArgs e)
{
PostThreadMessage(SQL_Thread.ManagedThreadId, WM_CX_NULL, 1, 1);
}
private void Form1_Load(object sender, EventArgs e)
{
msg = new tagMSG();
SQL_Thread = new Thread(new ThreadStart(this.SQL_ThreadExectue));
SQL_Thread.Priority = ThreadPriority.BelowNormal;
SQL_Thread.Start();
}
}
}
问题出在 SQL_Thread.ManagedThreadId
由于你调用的是Win32 API,这个API 无法识别管理线程,你必须发送消息到Windows的线程ID上,而不是管理线程的ID上。
修改你的的代码如下:
添加:
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
private int _SQLThreadId = 0;
修改:
public void SQL_ThreadExectue()
{
_SQLThreadId = GetCurrentThreadId();
//Thread.Sleep(50);
while (GetMessage(ref msg, 0, 0, 0) > 0)
{
if (msg.message == WM_CX_NULL)
{
MessageBox.Show("消息收到!");
}
}
}
修改:
private void button1_Click(object sender, EventArgs e)
{
PostThreadMessage(_SQLThreadId, WM_CX_NULL, 1, 1);
}
修改完后,我测试了一下,可以收到消息了。