17
paź/09
0

[C#] How to associate user component with other component which is null at initialization

Problem:

The idea is to put my own component on form and associate it with already existing TabControl object. Also, I wanted to capture user pressed keys and react on them before they will reach other controls (which require to set KeyPreview to true and add KeyDown/KeyUp event). Willing to encapsulate this process behind developer eyes, I write appropriate code in property of my component. But when I added control in Component Designer I was receiving error while starting application, initialize code of my component was written in InitializeComponent() method before the base Form object was initialized. Like this:


void InitializeComponent()
{
//....
//
// MyComponent
//
this.myComponent.ParentTab = this.tabControl1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(522, 273);
this.Controls.Add(this.tabControl1);
this.KeyPreview = true;
this.Name = "Form1";
this.Text = "Form1";
this.myComponent1.ResumeLayout(false);
this.ResumeLayout(false);
}

And in my code I was calling the uninitialized code:


//...
myComponent1.FindForm().KeyDown += //...

FindForm() was returning null (as the form wasn’t yet initialized)

Solution:

  1. Create KeyDown (or any) event for the TabControl itself
  2. At runtime, check in KeyDown state of the form you want to hook to. If it’s null, you can use the FindForm() because at runtime all controls are already initialized !

Solution was implemented in TabSwitcher component I wrote, for the TabControl control.

It’s that simple!

Komentarze (0) Trackbacks (0)

Brak komentarzy.

Przepraszam, dodawanie komentarzy zablokowane.

Brak trackbacków.