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();
} }
}
试了下,可以的啊,没什么问题
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();
} }
}
试了下,可以的啊,没什么问题
if(hwndPlc!=IntPtr.Zero)
{
SendMessage(hwndPlc, MY_MESSAGE1, 120, 220);
}
我的意思是如果没有这个串口,返回的不是null啊。
我采用if语句判断如果不等于0 就表示窗口存在。
如果不存在,返回0,我就不发送消息了!
API不是你自己封装实现的,所以想知道它到底是怎么工作的,需要查API文档说明.
{
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");不断的执行这句
代码。
高手救救我啊!