I have written an WinForms Control as ActiveX by COM-Interop and so far it works well in MS Access.
But the Problem is in Access the Form on the Display View hasn't the same Size as the Form in the Design View.
I have tried to set the Initialize Size by getting the ContainerControl. But i doesn't return the right Value.
public DummyCtrl()
{
this.Dock = DockStyle.Fill;
this.AutoSize = true;
var axC = (Control)this.GetContainerControl();
this.Width = axC.Width;
this.Height = axC.Height;
InitializeComponent();
}
GetContainerControl() contains a "ControlAxSourcingSite[WFControl.DummyCtrl]" Object.
I'm not sure how to get the right Value befor Initialize the Element. Any Ideas?
So i found it by myself. ;)
The right way to do this is:
public DummyCtrl()
{
this.Size = PreferredSize;
InitializeComponent();
}
I suggest that this works probably in every Forms Control.
Have a nice Day...
Related
I'm working on a Agenda using windows forms C#, I'm trying to create a colored picture box for each appointment object in the project. Using this code that is used in a loop for each object in my appointment list im creating each picturebox on the right location on the form1 screen.
PictureBox Point = new PictureBox();
this.Controls.Add(Point);
Point.Location = new Point(obj.Location.X, 45 + obj.Location.Y);
Point.BackColor = color;
Point.Size = new Size(96, 25);
Point.Enabled = false;
Point.Tag = "Point";
Point.TabIndex = 100;
Point.Visible = true;
When I'm calling this method from input on the same form, for example a button click. It will work just fine and create all the picture boxxes as needed. But when I'm calling it from the form2.closed event it wont work. Form 2 is my appointment planner form, when clicking on save on this form it will add a new object to the list, so a new picturebox should be created. I have checked the debug using breakpoints, and strange enough it will go through the create code, but no matter what I do it wont render the pictureboxxes.
I personally think it has to do with the form1 not Initializing when called from form2.closed event. But even when using InitializeComponent(); end Refresh(); inside my code it still doesnt work.
Am I using the wrong event or is there a specific call I need to make to generate the pictureboxxes?
Sorry if my post is lacking code or info, I'm not used to posting on stackoverflow, feel free to ask for more information if needed.
if you run your code from Form2 and you want to add control to Form1 you cannot use "this". Form1 has to be accessible from Form2.
PictureBox Point = new PictureBox();
Point.Location = new Point(obj.Location.X, 45 + obj.Location.Y);
Point.BackColor = color;
Point.Size = new Size(96, 25);
Point.Enabled = false;
Point.Tag = "Point";
Point.TabIndex = 100;
Point.Visible = true;
Form1.Controls.Add(Point);
I am new to Winforms and C# so this may sound like a stupid question. I have the class shown below for creating a form to be displayed as a modal dialog.
class FrmDelivery : Form
{
ListBox s;
public FrmDelivery()
{
s = new ListBox();
s.DataSource = new List<int>(){1,2,3,4};
s.Update();
s.Show();
}
}
However for some reson when I use the ShowDialogmethod to display this form it doesnt show anything in it. What should I do to add a list box to this form ?
EDIT:
I use the code to display the form:
FrmDelivery frm = new FrmDelivery();
frm.ShowDialog();
One note - WPF uses Windows, not Forms, so I'm not clear why you're deriving from Form rather than Window. But I'll answer as if you were talking about a WPF Window as your "form".
First, something will need to display the Window. Currently, the code provided doesn't show the Window, it attempts to show a ListBox.
Second, you either need to add a LayoutPanel to the window and add your ListBox as a child of the layout panel. Layout Panels come in many flavors, such as Grids and StackPanels and Canvases based on what type of layout you want.
Or, you can set the Content of the Window to be your ListBox. This will mean the only thing on the Window is your ListBox', so if you want multiple visual elements on yourWindow`, you'll need to use a layout panel.
The second approach would look like
this.Content = s;
For the first approach, I'd recommend reading up on Layout Panels in WPF. Here is one tutorial and here is the MSDN topic on layout. A google search will yield many more results.
I suggest you create a new form using Add|New Item|Windows Form.
You will then get a design surface to which you can add a listbox, and generated code which will initialize your form and listbox correctly. In particular your form and listbox will gain default sizes which they don't have currently.
Your code (in say Form1.cs) will then be similar to this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.listBox1.DataSource = new List<int> { 1, 2, 3, 4 };
}
public int? SelectedValue
{
get
{
return (int?)this.listBox1.SelectedValue;
}
}
}
Plus there will be a load of code in Form1.Designer.cs similar to
....
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(30, 37);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.listBox1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.listBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
And you could use your form like this:
private void button1_Click(object sender, System.EventArgs e)
{
using (var form = new Form1()) // you should dispose forms used as dialogs
{
if (DialogResult.OK == form.ShowDialog()) // optional (you could have OK/Cancel buttons etc
{
Debug.WriteLine(form.SelectedValue ?? -1);
}
}
}
You should not only add the controls to the collection but also set up his caracteristics.
Size & emplacement, at least.
class FrmDelivery : Form
{
ListBox s;
public FrmDelivery()
{
s = new ListBox();
s.Location = new System.Drawing.Point(0, 0); //relative to the parent control (not an absolute value, so)
s.Name = "listBox1";
s.Size = new System.Drawing.Size(120, 95);
s.DataSource = new List<int>(){1,2,3,4};
this.Controls.Add(s); //it will add it to the form but you can add it to another control, like panel.
}
}
Hope it will help
You need to add the listbox to the controls collection:
ListBox s;
public FrmDelivery()
{
s = new ListBox();
s.DataSource = new List<int>() { 1, 2, 3, 4 };
this.Controls.Add(s);
}
This will get the control onto your form for you, though there are a bunch of other properties you will likely want to set (e.g. to get it looking how you want) - as others have mentioned, you can see how the designer does this in the code behind by putting a listbox onto a form and examining the resulting code.
Please see if you have the InitializeComponent() in the default construct commented out. It usually initializes all the control of the form on FormLoad.
I would like to resize custom control according to items it content
This dont work for me:
public CustomControl()
{
InitializeComponent();
if (ErrorLimits == false && Range == false)
{
this.Size = new Size(100, 100);
this.Invalidate();
}
else
{
this.Size = new Size(250,250);
this.Invalidate();
}
}
It changing nothing, How can I achieve it?
Thanks!
The containing form will instantiate CustomControl and then set its properties in the form's InitializeComponent function. The property values set in the form's designer are applied after the constructor to CustomControl has finished (which, if you think about it, they'd have to be).
Since you are setting your custom sizes in the control's constructor, they're probably getting overridden by the designer values immediately afterwards before the form is displayed.
A better place to set the size is the UserControl.Load event, which occurs after the designer properties have been set.
An even better option would be to properly support auto sizing.
I am trying to implement the following behaviour:
On a form there is a tabcontrol. On that tabcontrol there is a treeview. To prevent scrollbars appearing, I would like the form to change its size according to the contents of the treeview when displayed for the first time.
If the treeview has too many nodes to be displayed on the default size of the form, the form should change it's size so that there is no vertical scrollbar on the treeview (up to a maximum size allowed by the size of the screen).
What I need to know is, if it is possible to achieve this behaviour through the properties of the controls. I'm sure this can be achieved by calculating and settings the sizes of the elements programmatically, but I would like to know if there is a way to achieve this by settings like AutoSizeMode etc.
[UPDATE]
It's the first dialog a user of my application sees: It's a dialog to select the database to work with. It's a list of databases, with a tabcontrol, buttens etc. If the list is too long, scrollbars appear and a colleague of mine wants them to disappear.
Use the AutoSize and AutoSizeMode properties.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.autosize.aspx
An example:
private void Form1_Load(object sender, EventArgs e)
{
// no smaller than design time size
this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
// no larger than screen size
this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight);
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
// rest of your code here...
}
By using the various sizing properties (Dock, Anchor) or container controls (Panel, TableLayoutPanel, FlowLayoutPanel, etc.) you can only dictate the size from the outer control down to the inner controls. But there is nothing (working) within the .Net framework that allows to dictate the size of a container through the size of the child control. I also missed this a few times and tried the AutoSize property, but it never worked.
So all you can do is trying to get this stuff done manually, sorry.
From MSDN:
To maximize productivity, the Windows Forms Designer shadows the
AutoSize property for the Form class. At design time, the form
behaves as though the AutoSize property is set to false,
regardless of its actual setting. At runtime, no special
accommodation is made, and the AutoSize property is applied as
specified by the property setting.
This might be useful.
It resizes a new form to a user control, and then anchors the user control to the new form:
Form f = new Form();
MyUserControl muc = new MyUserControl();
f.ClientSize = muc.Size;
f.Controls.Add(muc);
muc.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
f.ShowDialog();
You could calculate the required height of the TreeView, by figuring out the height of a node, multiplying it by the number of nodes, then setting the form's MinimumSize property accordingly.
// assuming the treeview is populated!
nodeHeight = treeview1.Nodes[0].Bounds.Height;
this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight);
int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight);
this.MinimumSize = new Size(this.Width, requiredFormHeight);
NB. This assumes though that the treeview1 is the only control on the form. When setting the requiredFormHeight variable you'll need to allow for other controls and height requirements surrounding the treeview, such as the tabcontrol you mentioned.
(I would however agree with #jgauffin and assess the rationale behind the requirement to resize a form everytime it loads without the user's consent - maybe let the user position and size the form and remember that instead??)
This technique solved my problem:
In parent form:
frmEmployee frm = new frmEmployee();
frm.MdiParent = this;
frm.Dock = DockStyle.Fill;
frm.Show();
In the child form (Load event):
this.WindowState = FormWindowState.Maximized;
If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.
this.contents.Size = new Size(this.ClientRectangle.Width,
this.ClientRectangle.Height);
I User this Code in my project, Useful for me.
private void Form1_Resize(object sender, EventArgs e)
{
int w = MainPanel.Width; // you can use form.width when you don't use panels
w = (w - 120)/4; // 120 because set 15px for each side of panels
// and put panels in FlowLayoutPanel
// 4 because i have 4 panel boxes
panel1.Width = w;
panel2.Width = w;
panel3.Width = w;
panel4.Width = w;
}
I used this code and it works just fine
const int margin = 5;
Rectangle rect = new Rectangle(
Screen.PrimaryScreen.WorkingArea.X + margin,
Screen.PrimaryScreen.WorkingArea.Y + margin,
Screen.PrimaryScreen.WorkingArea.Width - 2 * margin,
Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7));
this.Bounds = rect;
I want to show a new form in the same window from where it was invoked.
I know a way to show this form on PrimaryScreen or Virtual Screen by code similar to as below:
MyForm.Location = Screen.PrimaryScreen.Bounds.Location;
But i want to show it on current screen.
Is there a way to find out and show it on current screen?
I have done something like this to show my form centered to the current screen:
var screen = Screen.FromPoint(Cursor.Position);
myForm.StartPosition = FormStartPosition.Manual;
myForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - myForm.Width / 2;
myForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - myForm.Height / 2;
You can use the same technique, but instead of using the PrimaryScreen, grab the screen using Screen.FromPoint and Cursor.Position:
Screen screen = Screen.FromPoint(Cursor.Position);
MyForm.Location = screen.Bounds.Location;
It sounds like you aren't setting the StartPosition to Manual.
If you already have a parent form and want to open a new form on the same screen, give the ShowDialog method a reference to the parent form: newForm.ShowDialog(this); Without owner parameter ("this") the new form may open on the main screen even when your parent form is on another screen.
Click on the Form in design mode.
Change the StartPosition property to CenterScreen .
This should open up the form on the active screen. Refer
this for more values of StartPosition.
I know this is late, but still, post my answer hope that it will help someone else. After several tries, I got this work with 3 monitors
var currentScreen = Screen.FromControl(this);
if (!currentScreen.Primary)
{
var hCenter = currentScreen.Bounds.Left + (((currentScreen.Bounds.Right - currentScreen.Bounds.Left) / 2) - ((Width) / 2));
var vCenter = (currentScreen.Bounds.Bottom / 2) - ((Height) / 2);
StartPosition = FormStartPosition.Manual;
Location = new Point(hCenter, vCenter);
}
else
{
CenterToScreen();
}
Many years later, but no item was marked as the appropriate answer and I combined two comments to get it working (namely from Reed Copsey and Jason).
I haven't tried any of the other methods described, since this worked without problem and got the Form to open on the monitor my cursor is at, as intended.
Here's my working code:
Screen screen = Screen.FromPoint(Cursor.Position);
Application.Run(new Form1()
{
StartPosition = FormStartPosition.Manual, //Summary in VS actually mentions this as needed to make use of Location
Location = screen.Bounds.Location,
WindowState = FormWindowState.Maximized
});