如果找到所需的窗口句柄(即"DesiredWindow"
当前正在计算机上运行),我无法找出正确提升事件的方法而只有。只有在窗口句柄可以找到的情况下才会引发事件
目前,我的应用程序将SetForegroundWindow
并发送一个按键到正确的窗口,只要该应用程序正在运行;我的问题是:如果所需的窗口不可用(即目标应用程序未运行),它仍然会在发生事件时将按键发送到任何活动窗口,即使我已指定窗口句柄想要将其发送到,并且该窗口句柄在系统上不存在。
我想知道的是:如果特定的lpWindowName
存在,是否可以告诉我的应用程序只发送按键,并且如果指定的窗口名称找不到,什么也不做?
伪代码:
public partial class form1: Form
{
[DllImport("User32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr hWnd);
static IntPtr DesiredWindow = FindWindow(null, "(Desired Window Name)");
public form1()
{
InitializeComponent();
}
//...
private void MyEvent()
{
if (DesiredWindow cannot be found)
{
return; //Do not send KeyPress
}
SetForegroundWindow(DesiredWindow);
Thread.Sleep(50);
Keyboard.KeyPress(Keys.(WhateverKey));
}
}
我已经试过:
private void MyEvent()
{
if (!DesiredWindow)
{
MessageBox.Show("DesiredWindow not found");
return;
}
SetForegroundWindow(DesiredWindow);
Thread.Sleep(50);
Keyboard.KeyPress(Keys.WhateverKey);
}
但我得到的错误Operator '!' cannot be applied to operand of type 'IntPtr'
我也试过:
private void MyEvent()
{
if (DesiredWindow == IntPtr.Zero)
{
MessageBox.Show("DesiredWindow not found");
return;
}
SetForegroundWindow(DesiredWindow);
Thread.Sleep(50);
Keyboard.KeyPress(Keys.WhateverKey);
}
但是,当我使用这种方法时似乎没有发生。
我已将MessageBox.Show("DesiredWindow not found");
添加到if
声明中,让我知道它是否正常工作,但即使所需窗口可用,也会弹出消息框。
我已经试过另一种方法是:
private void MyEvent()
{
if (DesiredWindow > 0)
{
SetForegroundWindow(DesiredWindow);
Thread.Sleep(50);
Keyboard.KeyPress(Keys.WhateverKey);
}
}
但我得到的错误Operator '>' cannot be applied to operand of type 'IntPtr' or 'Int'
我不知道检查,看看是否存在DesiredWindow
的正确途径。
'else if(msg.Equals(“Message”))'这是什么..?你错过了一些代码..? – MethodMan
对不起,这正是触发我的事件的原因。这是一个TCP客户端/服务器应用程序,服务器根据从客户端收到的消息发送不同的击键。我想我会离开这部分,以避免混淆 – Patrick
@MethodMan我编辑的问题,以避免混淆事件引发,并添加更多的细节,我的尝试。 – Patrick