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;namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);        public void SendMessageToPlc()
        {
            IntPtr hwndPlc = IntPtr.Zero;
            //test
            label1.Text = hwndPlc.ToString();            hwndPlc = FindWindow(null, "Untitled - Notepad"); //找userdefinemessage的窗口            //test
            label2.Text = hwndPlc.ToString();            if (hwndPlc!=IntPtr.Zero)
            {
                MessageBox.Show("到这里了");
                return;
            }        }        private void button1_Click(object sender, EventArgs e)
        {
            SendMessageToPlc();
        }    }
}
试了下,可以的啊,没什么问题

解决方案 »

  1.   

    哦,想起来了,最近我也在做类似的,好像碰到过,仔细看看你的这段代码执行有没有问题。
    if(hwndPlc!=IntPtr.Zero)
                {
                    SendMessage(hwndPlc, MY_MESSAGE1, 120, 220);
                }
      

  2.   

    很有可能是没有找到这个窗口,API退不出来!
      

  3.   

    难道一定要找到这个窗口的吗?
    我的意思是如果没有这个串口,返回的不是null啊。
    我采用if语句判断如果不等于0 就表示窗口存在。
    如果不存在,返回0,我就不发送消息了!
      

  4.   

    我的意思是如果没有这个串口,返回的不是null啊
    API不是你自己封装实现的,所以想知道它到底是怎么工作的,需要查API文档说明.
      

  5.   

    既然获取这个窗口的句柄有问题,那我就想在获取之间来个判断以下是代码:  public void  SendMessageToPlc()
            {
                IntPtr hwndPlc = IntPtr.Zero;
                IntPtr hMutex;
                int kk = 0;
                hMutex = CreateMutex(null, false, "UserDefineMessage"); //判断是
                kk=GetLastError();            if (kk== ERROR_ALREADY_EXISTS)  //ERROR_ALREADY_EXISTS是常量183
                {
                    hwndPlc =FindWindow(null, "UserDefineMessage");               if (hwndPlc != IntPtr.Zero)
                    {
                        SendMessage(hwndPlc, MY_MESSAGE1, 120, 220);
                    }
                }
              
            }可是还是出了以前的问题,本来的话,如果窗口没有打开,GetLastError()应该返回的不是183,
    可是程序执行第一次好的,第二次以后就不行了。会返回183了,这样的话,就回到原来的问题了。
    如果窗口没有打开,就停在hwndPlc =FindWindow(null, "UserDefineMessage");不断的执行这句
    代码。
    高手救救我啊!
      

  6.   

    是不是你这个程序本身也处理了MY_MESSAGE1这个消息啊?要不没道理啊!