Change form position at runtime changing screen number - c#

I'm trying to change Form position to center after changing from a primary screen on a secondary screen
private void Form2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
ff = !ff;
if(ff)
showOnScreen(1,this);
else
showOnScreen(0,this);
}
}
void showOnScreen(int screenNumber,Form frm)
{
Screen[] screens = Screen.AllScreens;
if (screenNumber >= 0 && screenNumber < screens.Length)
{
Location = screens[screenNumber].WorkingArea.Location;
this.Location = new Point((screens[screenNumber].Bounds.Size.Width / 2) - (this.Size.Width / 2), (screens[screenNumber].Bounds.Size.Height / 2) - (this.Size.Height / 2));
}
}
The form is moved in center of screen but only in my primary screen

You need to set StartPosition manual of form to set start position value in Location Property.
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(0, 0);
}
Also Take Reference From Here and also check my Another Reference
Now
Try to setting WindowStartUpLocation parameter as "manual" inside your showOnScreen method.

Related

C# Form popup location

I am building a popup application to show some notification. I want to show it on the screen at the right-side bottom, in any screen resolution. The screen size is 422 x 217 (width x height). Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
/*System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer(); */
int num = 1;
this.Hide();
if (num == 1)
{
Form fm = new Form
{
Location = new Point(50, 60),
StartPosition = FormStartPosition.Manual,
ShowInTaskbar = false
};
fm.ShowDialog();
}
}
I want to make the popup as coming from bottom. Can anyone help me with this?
I recently got code for a 'toaster' popup which comes out from the bottom right corner of any screen. Here is part of the code-behind I used:
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
{
var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var corner = transform.Transform(new Point(workingArea.Right + 15, workingArea.Bottom - 10));
this.Left = corner.X - this.ActualWidth - 100;
this.Topmost = true;
this.Top = corner.Y - this.ActualHeight;
}));
Adjust the -100, +15 and -10 based on your 'popup' dimensions.

Grow windows form with button click

I want to grow a form when I click the button and it should be in the center of the screen .so I wrote following code snippet.
private void ord_Click(object sender, EventArgs e)
{
this.StartPosition = FormStartPosition.CenterScreen;
this.Size = new Size(1308,599);
this.Show();
}
But when I click the button window grows but half of the window can not see.Here is the picture of that.
GUI after growing
How can I get rid of this problem.?
Whats wrong with my code?
You have to compute both Size and Location:
private void ord_Click(object sender, EventArgs e) {
// Ensure that suggested form size doesn't exceed the screen width and height
this.Size = new System.Drawing.Size(
Screen.GetWorkingArea(this).Width >= 1308 ? 1308 : Screen.GetWorkingArea(this).Width,
Screen.GetWorkingArea(this).Height >= 599 ? 599 : Screen.GetWorkingArea(this).Height);
// locate the form in the center of the working area
this.Location = new System.Drawing.Point(
(Screen.GetWorkingArea(this).Width - Width) / 2,
(Screen.GetWorkingArea(this).Height - Height) / 2);
}
You can use the PrimaryScreen property of the Screen class.
//this.StartPosition = FormStartPosition.CenterScreen;
//this.Show();
Omit these lines you've written, except setting the Size property of the form:
private void ord_Click(object sender, EventArgs e)
{
this.Size = new Size(1308,599);
CenterForm();
}
Create a method named CenterForm() which will set a new location of the form. You can achieve this by calling this method in your button click event.
private void CenterForm()
{
int getWidth = Screen.PrimaryScreen.Bounds.Width;
int getHeight = Screen.PrimaryScreen.Bounds.Height;
int X = getWidth - this.Width;
int Y = getHeight - this.Height;
this.Location = new Point(X / 2, Y / 2);
}
Note: Always remember to anchor your controls when the size of the form has changed.

I did that the form1 will move slowly to the left. How can i make that it will start from the center of the screen?

At the top of Form1 i did:
private IntPtr ID;
private int counter = 0;
In the constructor i did:
ID = this.Handle;
timer2.Enabled = true;
Then in timer2 tick event i did:
private void timer2_Tick(object sender, EventArgs e)
{
if (counter <= Screen.PrimaryScreen.Bounds.Right)
MoveWindow(ID, counter++, 0, this.Width, this.Height, true);
else
counter = 0;
}
But the form start to move from the top left corner at 0,0 to the right.
I want the form will start to move from the center of the screen to the left untill it hit the left border/bound and stop and stay there.
How can i do it ?
I found now how to make it to move to the left and stop on the left border/bound:
private void timer2_Tick(object sender, EventArgs e)
{
if (counter >= Screen.PrimaryScreen.Bounds.Left)
MoveWindow(ID, counter--, 0, this.Width, this.Height, true);
else
counter = 0;
}
But how do i make that it will start to move from the middle/center of the screen ?
I did in the designer change the property: StartPosition to CenterScreen
But the form start to move from the top left corner 0,0
There is a better solution for you, just use the protected method CenterToScreen() like this:
this.CenterToScreen();
This is the answer.
x = Screen.PrimaryScreen.Bounds.Bottom - this.Width * 2;
y = Screen.PrimaryScreen.Bounds.Bottom - this.Height * 2;
counter = x;
Then in the timer tick event:
private void timer2_Tick(object sender, EventArgs e)
{
if (counter >= Screen.PrimaryScreen.Bounds.Left)
MoveWindow(ID, counter--, y, this.Width, this.Height, true);
else
counter = 0;
}
Before it the counter-- was set to 0. And instead y it was 0 too.
So it's 0,0 this is the location.
Now counter and y start location is the middle of the screen.
Thanks.
You could set the StartPosition property of your main WinForm to CenterScreen:
Form1.StartPosition = FormStartPosition.CenterScreen;
Then if you want it to appear somehow on a different position relative to this screen center, you can play with the Top and Left properties to add or subtract the required number of pixels.
if you need to know the screen bounds:
System.Windows.Forms.Screen.PrimaryScreen.Bounds
or, taking into account the task bar:
System.Windows.Forms.Screen.PrimaryScreen.WorkingArea
...or some variant

Width of the form can not be less than 140 pixels. Why?

I created default Windows Forms Application project in Visual Studio 2012. When I run program then saw that width of form can not be less than 140 pixels. Why? And how to overcome this strange restriction?
I was looking for a solution and MinimumSize(0,0) didn't had any effect. Figured out, that MinimumSize set to (1,1) actually fixed the problem and after showing my form it was properly sized smaller than 140px.
Column click event on (ListView)_csvLv that should trigger a popup dialog:
var topAnchor = _csvLv.PointToScreen(new Point(
_csvLv
.Columns
.OfType<ColumnHeader>()
.Where(c => c.DisplayIndex < e.Column)
.Sum(c => c.Width),
0));
Left = topAnchor.X;
Top = topAnchor.Y;
MinimumSize = new Size(1,1);
ClientSize = new Size(_csvLv.Columns[e.Column].Width, 100);
ShowDialog();
Users wouldn't be able to use the window's minimize, maximize, and close buttons at that top. I don't believe you can change that behaviour with the Sizable FormBorderStyle. It's a usability thing.
If you remove the border, by setting it to None for example, you can set it to whatever you want programmatically by doing:
form.Width = [...];
You can resize further forms with border types: None, FixedToolWindow, and SizableToolWindow. The ToolWindows won't let you go below a certain amount as well, but None will let you do anything above 2px. You could set it to some value below that, without getting an exception, but it won't do anything.
Try this.
Autosize no
AutosizeMode growOnly
FormBorderStyle SizableToolWindow <== this one did it
I still can move the form and resize it (width) less tan 112
I never use formborders.. I always like to go with FormBorderstyle.None
To resize, you have to add some code.
Put a pictureBox, add a grip img in it and place it in the corner.
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += new MouseEventHandler(Form1_MouseDown);
pictureBox1.MouseMove += new MouseEventHandler(Form1_MouseMove);
pictureBox1.MouseUp += new MouseEventHandler(Form1_MouseUp);
}
void Form1_MouseUp(object sender, MouseEventArgs e)
{
isHolding = false;
}
void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (isHolding)
{
int diffX = this.Width - pictureBox1.Left;
int diffY = this.Height - pictureBox1.Top;
pictureBox1.Left += e.X - curX;
pictureBox1.Top += e.Y - curY;
this.Width = pictureBox1.Left + diffX;
this.Height = pictureBox1.Top + diffY;
}
}
void Form1_MouseDown(object sender, MouseEventArgs e)
{
isHolding = true;
curX = e.X;
curY = e.Y;
}
int curX = 0, curY = 0;
bool isHolding = false;

FormStartPosition.CenterParent does not work

In the following code, only the second method works for me (.NET 4.0). FormStartPosition.CenterParent does not center the child form over its parent.
Why?
Source: this SO question
using System;
using System.Drawing;
using System.Windows.Forms;
class Program
{
private static Form f1;
public static void Main()
{
f1 = new Form() { Width = 640, Height = 480 };
f1.MouseClick += f1_MouseClick;
Application.Run(f1);
}
static void f1_MouseClick(object sender, MouseEventArgs e)
{
Form f2 = new Form() { Width = 400, Height = 300 };
switch (e.Button)
{
case MouseButtons.Left:
{
// 1st method
f2.StartPosition = FormStartPosition.CenterParent;
break;
}
case MouseButtons.Right:
{
// 2nd method
f2.StartPosition = FormStartPosition.Manual;
f2.Location = new Point(
f1.Location.X + (f1.Width - f2.Width) / 2,
f1.Location.Y + (f1.Height - f2.Height) / 2
);
break;
}
}
f2.Show(f1);
}
}
This is because you are not telling f2 who its Parent is.
If this is an MDI application, then f2 should have its MdiParent set to f1.
Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.MdiParent = f1;
f2.Show();
If this is not an MDI application, then you need to call the ShowDialog method using f1 as the parameter.
Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.ShowDialog(f1);
Note that CenterParent does not work correctly with Show since there is no way to set the Parent, so if ShowDialog is not appropriate, the manual approach is the only viable one.
If you set the owner of the child form like so:
Form2 f = new Form2();
f.Show(this);
You can then center it easily like this:
Form2_Load(object sender, EventArgs e)
{
if (Owner != null)
Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2,
Owner.Location.Y + Owner.Height / 2 - Height / 2);
}
I'm using this code inside my main form, hope it helps:
var form = new MyForm();
form.Show();
if (form.StartPosition == FormStartPosition.CenterParent)
{
var x = Location.X + (Width - form.Width) / 2;
var y = Location.Y + (Height - form.Height) / 2;
form.Location = new Point(Math.Max(x, 0), Math.Max(y, 0));
}
I found setting the location manually is the only reliable option in some more complex cases when form is auto-sized and dynamically modified.
However rather than computing the coordinates manually, I'd suggest using existing method:
this.CenterToParent();
I had the same problem, I eventually went with this:
protected override void OnActivated(EventArgs e) {
if(this.Modal == false && this.StartPosition == FormStartPosition.CenterParent) {
if(!(this.Owner is Form)) {
// Center to the last form opened before this one
int numforms = Application.OpenForms.Count;
this.Owner = Application.OpenForms[numforms - 2];
}
this.CenterToParent();
Application.DoEvents();
}
base.OnActivated(e);
}
Used as:
MyForm form = new MyForm();
form.Show(this); // with or without
The main advantage is that it does what your colleagues expect it to do, without requiring any hack in the calling form.
I found a solution that will center modeless window position to parent's position, and the child window can be still covered by parent window.
You just have to call
f2.Show(f1);
which will set f2 owner to f1, f2 will show over the f1 at it's center position.
Next you set
f2.Owner = null;
and there you go, f2 is a separate window, with correct startup position.
I realize this is an old question, but I was recently having the same problem and for reasons I won't get in to, I did not want to use the form.ShowDialog() method and my application was not an MDI application, therefore the CenterParent method was not having any effect. This is how I solved the problem, by computing the coordinates for the form that I wanted centered and triggering the new location in the main form's LocationChanged event. Hopefully this will help someone else having this problem.
In the example below, the parent form is called MainForm and the form I want centered in MainForm is called pleaseWaitForm.
private void MainForm_LocationChanged(object sender, EventArgs e)
{
Point mainFormCoords = this.Location;
int mainFormWidth = this.Size.Width;
int mainFormHeight = this.Size.Height;
Point mainFormCenter = new Point();
mainFormCenter.X = mainFormCoords.X + (mainFormWidth / 2);
mainFormCenter.Y = mainFormCoords.Y + (mainFormHeight / 2);
Point waitFormLocation = new Point();
waitFormLocation.X = mainFormCenter.X - (pleaseWaitForm.Width / 2);
waitFormLocation.Y = mainFormCenter.Y - (pleaseWaitForm.Height / 2);
pleaseWaitForm.StartPosition = FormStartPosition.Manual;
pleaseWaitForm.Location = waitFormLocation;
}
If you have a resizable parent form and you wanted your sub form to also be centered whenever the main form is resized, you should, in theory, be able to place this code in a method and then call the method on both the LocationChanged and SizeChanged events.
JYelton's answer worked for me, but the form is only centered the first time Show() is called.
If you want to Hide() the form, and then have it re-centered on the parent every time Show() is called you need use the following in your form:
public new void Show(IWin32Window owner)
{
base.Show(owner);
if (Owner != null)
Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2,
Owner.Location.Y + Owner.Height / 2 - Height / 2);
}
Maybe this can help somebody.
Form frmMessage = new Form();
From experience, although they look similar, they behave different:
This variant doesn't work:
if (frmMessage.Parent != null)
frmMessage.CenterToParent();
else
frmMessage.CenterToScreen();
And this variant works
if (frmMessage.Parent != null)
frmMessage.StartPosition = FormStartPosition.CenterParent;
else
frmMessage.StartPosition = FormStartPosition.CenterScreen;
Using
form.Show(this);
throws an exception if you call it a second time. Manually setting the location seems to be the only reliable option :/ (wasn't it fairly recently that CenterParent used to work?)
just put the code in the constructor of your form.
public FrmSample()
{
InitializeComponent();
// must be after the InitializeComponent()
this.StartPosition = FormStartPosition.CenterParent;
}
Small Change to JYelton's answer
Form2_Load(object sender, EventArgs e)
{
if (Owner != null && Parent == null && StartPosition == FormStartPosition.CenterParent)
Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2,
Owner.Location.Y + Owner.Height / 2 - Height / 2);
}
An old question, I know, but I had the same issue but for a different reason.
The Form I was opening had an overridden OnLoad method:
protected override void OnLoad(EventArgs e)
{
//... etc.
}
but was not calling the base implementation as it must do:
protected override void OnLoad(EventArgs e)
{
//... etc.
base.OnLoad(e);
}
When overriding OnLoad(EventArgs) in a derived class, be sure to call the base class's OnLoad(EventArgs) method so that registered delegates receive the event.
Building off the answer by deerchao,
if (form.StartPosition == FormStartPosition.CenterParent) {
form.Location = new Point(Location.X + (Width - form.Width) / 2, Location.Y + (Height - form.Height) / 2);
}
Do this after form.Show(), this will work on multi-monitors also

Categories