Form designer in visual studio overrides my code - c#

I made my toolstrip too narrow. I went into the Form1.Designer.cs and tried to fix it. I found:
this.toolStrip1.Size = new System.Drawing.Size(284, 25);
and changed 25 to 55. When I run visual studio again it tells me that the code changed, and asks me if I want to run it. But it seems like the graphical design tool somehow overrides my changes, because the with stays the same when I run the application again.
I found this interesting bit of code in the Form1.Designer.cs
#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()
{
Is there something I can do there to make the graphical design tool not able to change my code?
Yeah I also tried the most obvious solution by trying to change the layout in the graphical tool itself, but I can't re-size the toolstrip there

set AutoSize property to false
this.toolStrip1.AutoSize = false;
this.toolStrip1.Size = new System.Drawing.Size(284, 55);

Related

How Do You Edit a Second (Non-Main) C# Form Window In Visual Studio Designer?

I am writing a C# Windows Forms program in Visual Studio. I have a button that creates and shows (opens) a new Form (window) called VideoWindow. I can edit the MainWindow in the Design workspace in Visual Studio which allows me to visually edit its contents. However, I can't find a way to do the same thing with the VideoWindow. I have tried right clicking on VideoWindow and clicking View Designer, but it just takes me to the MainWindow designer. How do I open the designer for the second VideoWindow? Is this possible? Below is the code that creates and opens the new form:
private void ButtonWindow(object sender, EventArgs e)
{
Form VideoWindow = new Form();
VideoWindow.Size = new Size(500, 300);
VideoWindow.Show();
}
Edit: I know you can (and usually should) access the Designer when you create a form through the Visual Studio wizard via Project -> Add Form. However my question was for if you manually write a form class like NewForm.cs. In that case there would be no auto-generated NewForm.Designer.cs file.
You can customize a new form, and then create the corresponding object after modification. Here are the relevant steps:
1.Create a new form videoform
2.Relevant code:
.Show(); and .ShowDialog();
Note the difference between the two.
private void button1_Click(object sender, EventArgs e)
{
VideoWindow videoWindow = new VideoWindow();
videoWindow.Show();
//videoWindow.ShowDialog();
}
3.Ouput:
After some testing I found that it is possible to access the Visual Studio GUI-based Designer for a form class that was created manually (i.e. not created through the usual Project -> Add Form wizard).
If you create a CustomForm.cs file in your project and, importantly, have that class inherit from Form (System.Windows.Forms), then hit Shift F7, Visual Studio will make a GUI Designer for that form.
It will also automatically create the InitializeComonent method in CustomForm.cs and add the SuspendLayout and ResumeLayout calls and Client size, and Name properties in that method.
In this arrangement, the designer elements will not be separated from the class definitions in a separate form.Designer.cs file like usual. Any change through the Designer GUI will directly effect CustomForm.cs. Of course this is less than ideal because there's a higher likelihood of a developer breaking the form since the auto-generated code is mixed in with the manually written code.

How can I add a button to the layout? - C# [duplicate]

This question already has answers here:
How to add buttons dynamically to my form?
(8 answers)
Closed 2 years ago.
I cannot find any methods to add the button to the layout.
I am trying to add the child (button) to the layout, but I can't find any methods to do so.
Source Code:
using System;
using System.Windows.Forms;
namespace WinForms
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Button button = new Button {Height = 100, Width = 100, Text = "Test"};
}
}
}
You open your project in Visual Studio 2019 (not Visual Studio Code, not JetBrains Rider) - free versions for which exist if your context qualifies for the license. If you don't qualify for a free license, you[r workplace] can easily afford a license of some form
You double click Form1 in the solution explorer and then you see something that looks like what the form will look like when you run the program, and you open the controls tool panel and drag a button out of it and drop it onto the form...
But if you want to get into hand-writing the volumes of boring repetitive code to build a UI then you add controls to the Controls collection of other controls, viz:
Form1 f = new Form1();
Button button = new Button {Height = 100, Width = 100, Text = "Test"};
f.Controls.Add(button);
Application.Run(f);
Every Control has a Controls collection to which other Controls can be added (not just things you think of as "things that have child controls, like Panel or GroupBox" - some controls are collections of other controls, like a NumericUpDown is a textbox and a couple of buttons)
For an example of how much code you'll need to write, lay out a reasonable looking UI in the design view and then open the Form1.Designer.cs - you'll see why we do it with the aid of a design tool! :)
Wouldn't it be faster to learn if I didn't use the Designer tool?
IMO, no. That's like saying "wouldn't it be faster to learn if I hand code an SVG in notepad rather than using Inkscape/Gimp to draw the image visually.. or create a PNG by typing the bytes out in a hex editor"
Getting so close to the raw low level means you end up "not being able to see the wood for the trees" and it hinders your learning. For a lengthy discourse on abstractions and why we use them/how they apply to every daily process including learning and operating in life, see the comment trail
You need to add the button to your Form, not to the Main method!
The issue with your code is that it's in the wrong place - actually, it only runs after the form is closed, because Application.Run will run your form in a message loop, allowing UI events to fire.
You can either use the Visual Studio WinForms Designer (if using Visual Studio), or manually add the code after the InitializeComponent() method - so, either right in the constructor, or in any of the Form startup events, such as Load or Shown.
It's likewise very important to add the Button (or any dynamically instantiated control, for that matter) to the Controls collection of the Form - otherwise, your Button won't be displayed:
Button button = new Button {Height = 100, Width = 100, Text = "Test"};
this.Controls.Add(button);
There are certainly use cases for dynamic generation of controls; however, it's very unusual to build out your controls manually before the form even runs - in most cases of dynamic control generation, the form is up and running - the dynamic generation is in response to some user action. I recommend using the designer for general UI layout.

Why does visual studio remove static from my code?

I've manually set a label to a 'static', when I run the code it works fine but the next time I run the code it gives me a build error, this is because the 'static' got removed automatically.
I edited this in the formMain.Designer.cs file.
I looked on google and in Visual Studio itself but didn't find anything.
Here is a link to Paste-bin as the code would take to much space:
https://pastebin.com/LkPwrJhY
public static System.Windows.Forms.ToolStripStatusLabel lblSerialStatus;
The label I changed is on the last line of code, 'lblSerialStatus', at line 180.
I'm changing this label because I want to change it from an other form.
Thank you in advanced!
This is because formMain.Designer.cs file is auto-generated. Meaning every time you change something in the visual designer this file gets re-generated over writing any manual changes done to the file
If you really want the label somewhere else you'll need to pass it as a parameter to some method. Also, static UI elements make no sense, because the UI will not always be there or be accessible
Changing Designer.cs file is not recommended. The file is automatically generated and it will be generated again whenever you change the corresponding forms file.
look before InitializeComponent() its also mentions in your generated designer Code
#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>
If you want then you can create another file which contains a partial class where you can put all such logic or function

Appropriate way to force loading of a WPF Visual

I have been struggling with printing using the System.Printing namespace. I have finally figured out that the reason I was getting blank results when using portions of the API was because the Visual objects I was trying to print were not Loaded/Initialized. If I display the Visual objects by putting them in an appropriately-sized Windows and calling Show() prior to printing, I then get the expected results.
Thus, the workaround I came up with was to call this method for every Visual
public static void ShowVisual(Visual visual)
{
Window window = new Window
{
Content = visual,
SizeToContent = SizeToContent.WidthAndHeight,
Visibility = Visibility.Hidden
};
window.Show();
window.Close();
}
This seems like a hack, especially since the user briefly sees the Window-frame draw. I figure there must be a different way it is supposed to be done. However, I am not turning up any other solutions. Is using a hidden Window really what is supposed to be done here?
Using a MenuItem as described at WPF - Get size of UIElement in Memory? does not work. I looked at Force rendering of a WPF control in memory but I am not really wanting to render the Visual to a bitmap which seems to be what that is for. Calling ApplyTemplate() on the Image that as described in wpf force to build visual tree did not help.
EDIT: This is the solution that is used instead of ShowVisual from above
/// <remarks>
/// This method needs to be called in order for
// the element to print visibly at the correct size.
/// </remarks>
private static void ArrangeElement(UIElement element)
{
var box = new Viewbox {Child = element};
box.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
box.Arrange(new Rect(box.DesiredSize));
}
The items you want to print need to be added to the visual tree in WPF in order for the Measure and Arrange processes to be called on all the elements in the visual tree you want to show / print or otherwise display.
I haven't done this for a while but you may find that adding these items to a ViewPort in the background and then printing them solves the issue. This should get around the need for actually displaying them on the screen and thus the user seeing them whilst also forcing the Measure / Arrange processes.
I had the same problem. In my case I only call: Visual.UpdateLayout() before trying to work with it. As said by Jammer, it will automatically force Measure / Arrange processes.
I did it on window. If you have any problem, you probably should set the Visual Height and Width before call UpdateLayout().
Eric
I had the same issue. Solved by ApplyTemplate().
It force to builds visual tree of an Framework element.

Prevent Visual Studio from updating specific lines in Form.Designer.cs

I was wondering is it possible to prevent Visual Studio from updating specific lines that are changed by me?
For example i have separate resource only project (images, sounds, etc). I change some lines in Form.Designer.cs and make so all images are loaded from resource dll. But once i update Form it self everything goes back to default and all resources that were used by form gets copied to Form.resx file.
How could i solve this?
Nope.
As stated in the begining of the file, the *.Designer.* is an auto generated file. It's rebuilt every time that the file it depends upon is saved, so you should never change any code there that you don't want to be messed.
It is preferable to separate the code that the form designer generates from the code that you want to have some control over. The order in which you need to address this code can then be handled within the constructor of the form. Example:
namespace FormTest
{
public partial class Form1 : Form
{
private Label PostAddedLabel;
public Form1()
{
InitializeComponent();
PostInitializeComponents();
}
private void PostInitializeComponents()
{
if (!this.DesignMode)
{
PostAddedLabel = new Label();
PostAddedLabel.Left = 100;
PostAddedLabel.Top = 30;
PostAddedLabel.Text = "The Post-added Label";
this.Controls.Add(PostAddedLabel);
}
}
}
}
We can simply design the form within the designer, after a successful design phase we then can MOVE the declaration, assignments and related code that we want to separate to the PostInitializeComponents method.
By using the !this.DesignMode decision, the form will show the separated controls in Runtime mode. When in designer-mode these controls will not be shown, assuring that the system will not affect these controls when designing the form.
In case you want to use this methodology also in usercontrols, try to embed the "IsDesignerHosted" method over "DesignMode" from the following article: DesignMode with Controls
Hope this answers the question?
No. Visual Studio does not "update" the Designer file, it deletes it and writes an all new copy. No possible way to do what you want.
You should add your code to your code behind. It's the same class.

Categories