views:

127

answers:

1

I'm working on an app that shows its forms as a series of modal windows stacked on eachother. All forms are placed to the center of the screen. When the user moves the form around the screen, only the topmost one moves, others remain at the center and cannot be moved as they are blocked by the topmost dialog.

I'm trying to code a form-moving code that would move all the forms to the new location and also code that would open new forms at the current, non-centered location.

But something wierd happens when doing the latter - opening a new form in a non-centered position using Location of some other form (the bottom-most form). If I set the Location property of the form programatically, its size changes - the form gets smaller. Its Size property is changed from (240, 320), as set in the Designer GUI, to the smaller ClientSize (234, 294), which is present in the Designer-generated code. I've only found one post on the net referencing this problem, but no answers to it. If I leave the Location property alone, the Form is displayed correctly with the original size.

The StartPosition of the form is set to Manual, FormBorderStyle is FixedSingle, AutoScaleMode is either DPI or Font (I don't know gow to set this one).

Any ideas? Thanks.

+2  A: 

I'll answer my own question. It seems that the behaviour stems from setting the Location property while the form is not yet formed by the OS, that is, it doesn't have a handle created yet and its IsHandleCreated is False. I've debugged into .NET code itself and there was a Debug.Assert call with "Do not use this before CreateHandle" or something like that as the assert parameter somewhere on the call stack around the code that was problematic. This gave me the first hint.

Putting the code into an event handler for the Form.Load event fixed the problem. At the time that Load fires, the handle is already created and everything seems to function.

Now that I know the cause, I've searched the net a bit for "Constructor vs. Load event handler initialization" and the relevant discussions imply that you need to defer handling of controls until Load. Which kinda makes sense because .NET controls are wrappers around entities outside in the OS (and those need to be created to be usable) but at the same time doesn't make sense because the Designer code seems to be able to access controls before the handle is created just fine. If that makes any sense..

TLDR: defer control access and use until Form.Load event fires.

Jurij