日期:2014-05-18  浏览次数:21001 次

SendMessage 发送按键消息不成功
我在第一个From中用SendMessage发送一个消息给第二个From,可是第二个From没有触发这个事件,为什么呢?它没有收到消息么?

第一个窗口的核心代码:
C# code

   public const int wmmsg = 0x0100;
   for (int i = 0; i < pros.Length; i++)
   {
          if (pros[i].MainWindowTitle == "From2")
          {
            IntPtr hwnd = pros[i].MainWindowHandle;
            IntPtr dataint;
            SendMessage(hwnd, wmmsg, dataint, (IntPtr)0);
          }
   }



第二个窗口的:

private void NRCServer_KeyDown(object sender, KeyEventArgs e)
{
  RecString = Convert.ToString(e.KeyValue);
  label1.Text = RecString;
}

请问是哪一句出了问题?

------解决方案--------------------
c#程序没必要用SendMessage之类的api函数,
------解决方案--------------------
C# code
    private IntPtr _FromHandle = IntPtr.Zero;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.Show();
            _FromHandle = frm.Handle;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SendMessage(_FromHandle, wmmsg, (IntPtr)3, (IntPtr)1);
        }

------解决方案--------------------
C# code

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace SendMessageTest
{
    public partial class Form1 : Form
    {
        public const int wmmsg = 0x0100;
        [DllImport("user32.dll ", EntryPoint = "SendMessage")]
        static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, string lParam); 
        public Form1()
        {
            InitializeComponent();
        }
        Form2 f2;
        private void button1_Click(object sender, EventArgs e)
        {
            f2 = new Form2();
            f2.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SendMessage(f2.Handle, wmmsg, 0, "");
        }
    }
}

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;

namespace SendMessageTest
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_KeyDown(object sender, KeyEventArgs e)
        {
            MessageBox.Show(e.ToString());
        }
    }
}