0

I work on a C# Winform project.

I don't know what is different among

  1. this.ActiveControl = XControl;
  2. XControl.Focus();

Sometimes XControl.Focus() do not work and I have to set this.ActiveControl = XControl. I don't know why it happens. I'm confused, can anyone help me?

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103
ArMaN
  • 2,306
  • 4
  • 33
  • 55

1 Answers1

2

The documentation is rather clear about this:

Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

So it sounds like you should be setting the ActiveControl property. It is probably doing something extra that Focus does not do.

You could look in the Reference Source to find out exactly what, but that seems like a waste of time to me. It is always better to follow the documented behavior, rather than relying on implementation details.

Armed only with the information in the documentation and what I know about Windows programming, I can make a pretty good guess that the Focus method simply calls the Win32 SetFocus function, whereas the ActiveControl property probably has a bunch of additional logic to handle cases where calling SetFocus directly will not work.

For example, the linked documentation for SetFocus is very explicit about the fact that the window to which you are setting focus must be attached to the calling thread's message queue. The ActiveControl property might work around that. Or, it might have code that handles nested controls.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574