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);
}
}