WHen the applicaiton is running, how to keep checking which is the active window simultaneously?
My application uses SendKeys
to navigate through and enter data into the input fields (I know that is not the bestway to do it, but I have to work with t开发者_运维技巧his limitation). Now, I want to make sure that the correct window is active when the SendKeys
are at work.
One way to do confirm this is to check for the current active window before every SendKeys
commmand. But that sounds very exhaustive? Is there a better way to do this? I don't know much but am guessing using Multithreading? Any ideas?
As far as I understand from your post you send messages to windows that do not belong to your application. If so, then I'm afraid you have to check active window before every SendKeys call.
I think you will have to either check to see what has focus before you call SendKeys, or keep track of what has the focus yourself using OnGotFocus and OnLostFocus. Multithreading isn't going to help you here- only the GUI thread can interact with the GUI. So you could have a background thread doing work, but it has to delegate any interactions with the GUI. You can do this by calling BeginInvoke on any control or window and it will run the delegate in the right thread.
Edit: Ohh. I missed that you do not "own" the window in question. The code below will therefore not work. You need to continue doing what you are doing. You could always invoke SetForegroundWindow before every sendkeys.
Let the class that use SendKeys hook the Activated and Deactivated events from the form in question.
internal class SendKeysClass
{
private bool _canSend;
public SendKeysClass(Form form)
{
form.Activated += (sender, args) => _canSend = true;
form.Deactivate += (sender, args) => _canSend = false;
}
public void Send(string keys)
{
if (!_canSend)
return;
SendKeys.Send(keys);
}
}
Or if you are not using .Net 3.5 / C# 3.0:
internal class SendKeysClass
{
private bool _canSend;
public SendKeysClass(Form form)
{
form.Activated += OnActivated;
form.Deactivate += OnDeactivated;
}
private void OnDeactivated(object sender, EventArgs e)
{
_canSend = false;
}
private void OnActivated(object sender, EventArgs e)
{
_canSend = true;
}
public void Send(string keys)
{
if (!_canSend)
return;
SendKeys.Send(keys);
}
}
If you have a repetetive task, make a function out of it...
Warning: Just coded without any checking about correctness of function calls, etc.
void MySendKeyFunc(string windowTitle, IEnumerable<Keys> keys)
{
if(!GetForegroundWindow(windowTitle)
{
SetForegroundWindow(windowTitle);
}
foreach(Key key in keys)
{
SendKeys(key);
}
}
精彩评论