How to resize form in scale? C# - c#

i need that in my form the width is twice the height (1:2) also when i resize
How i can do that?
Thanks for help and sorry for my english :)

Check out this post: Resizing forms while keeping aspect ratio.
The key is to respond to the WM_SIZING message, it allows you to change the window rectangle.
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
// Necessary to take the window frame width/height into account
this.chromeWidth = this.Width - this.ClientSize.Width;
this.chromeHeight = this.Height - this.ClientSize.Height;
this.ClientSize = new System.Drawing.Size(400, 200);
}
// ...
#region Resizer
private float constantWidth = 2;
private float constantHeight = 1;
private int chromeWidth;
private int chromeHeight;
// From Windows SDK
private const int WM_SIZING = 0x214;
private const int WMSZ_LEFT = 1;
private const int WMSZ_RIGHT = 2;
private const int WMSZ_TOP = 3;
private const int WMSZ_BOTTOM = 6;
struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SIZING)
{
RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
int w = rc.Right - rc.Left - chromeWidth;
int h = rc.Bottom - rc.Top - chromeHeight;
switch (m.WParam.ToInt32()) // Resize handle
{
case WMSZ_LEFT:
case WMSZ_RIGHT:
// Left or right handles, adjust height
rc.Bottom = rc.Top + chromeHeight + (int)(constantHeight * w / constantWidth);
break;
case WMSZ_TOP:
case WMSZ_BOTTOM:
// Top or bottom handles, adjust width
rc.Right = rc.Left + chromeWidth + (int)(constantWidth * h / constantHeight);
break;
case WMSZ_LEFT + WMSZ_TOP:
case WMSZ_LEFT + WMSZ_BOTTOM:
// Top-left or bottom-left handles, adjust width
rc.Left = rc.Right - chromeWidth - (int)(constantWidth * h / constantHeight);
break;
case WMSZ_RIGHT + WMSZ_TOP:
// Top-right handle, adjust height
rc.Top = rc.Bottom - chromeHeight - (int)(constantHeight * w / constantWidth);
break;
case WMSZ_RIGHT + WMSZ_BOTTOM:
// Bottom-right handle, adjust height
rc.Bottom = rc.Top + chromeHeight + (int)(constantHeight * w / constantWidth);
break;
}
Marshal.StructureToPtr(rc, m.LParam, true);
}
base.WndProc(ref m);
}
#endregion
}

Use a TableLayoutControl to host your other controls. This works similarly to the HTML table.
You add your controls to a cell in the table, and then you can add ColumnStyles and RowStyles in which you can set the width and height of the cells. The measurments can be specified as auto, absolute or percentage. Percentage is the one that you really need here.
You then set this TableLayoutControl's dock to resize with your window, and the cells will get resized proportionally according to the percentages you set earlier.
To have the actual components resize as well, you have to set either of their Dock or Anchor properties. Any configuration that specifies how a control should be resized with respect to the cell it's in will work, e.g. you might want to have the controls resize only vertically in the cell and still remain the same width by setting the control's Anchor property to
AnchorStyle.Top | AnchorStyle.Bottom
In a nutshell:
Set how the control will be resized with respect to its cell
Set how the cells will be resized with respect to the TableLayoutControl (using ColumnStyles and RowStyles)
Set how the TableLayoutControl will be resized with respect to the form
More information can be found here: http://msdn.microsoft.com/en-us/vstudio/bb798032.aspx

Checkout the Control.Resize event -- also
private void Form1_Resize(object sender, System.EventArgs e)
{
Control control = (Control)sender;
control.Width = control.Height * 2;
}

Register to the resize event and literally do this:
this.ClientSize.Width = this.ClientSize.Height * 2;
or for the full form size (including borders)
this.Size.Width = this.Size.Height * 2;

You can use events such as onLoad, onClick and so others, to do resizing on certain conditions. So basically its up to you then.
There is some standard form properties height and width, so you can adjust these properties.
For example:
private void frmMain_Load(object sender, EventArgs e)
{
int height = 500;
frmMain.ActiveForm.Height = height;
frmMain.ActiveForm.Width = height / 2;
}

for resize the form below is better one
http://niravdaraniya.blogspot.in/2013/07/how-to-resize-form-in-cnet.html

Related

C# Application to Zoom in/out the image in a PictureBox

I am somewhat new to programming in general, but I am eager to learn more and I was wondering if anyone could possibly help me out with an idea.
(main goal)
I want to make a simple program that consists of a C# Windows Forms Application that displays a preset image (of 6000x6000 pixel dimensions, SizeMode set to Zoom so the entire image is visible on the form at once) in a PictureBox that will take up the entire form practically, save for a space at the bottom of the form where I want to display a TrackBar that will allow you to zoom the image in and out; as well as a horizontal scroll bar at the base of the PictureBox, and a vertical scroll bar on the right side of the PictureBox to scroll around the map when it is zoomed, and I wanted to be able to control these scroll bars by either clicking and dragging in a corresponding direction on the PictureBox (preferred but not sure if its possible) or by using the scroll wheel on the mouse (probably easier but once again not sure).
(reference)
[ Here is my form completed exactly as I described, with a 6000x6000 placement holder demo texture in a PictureBox using SizeMode Zoom, as an example - THIS HAS BEEN HANDLED, NEXT PART OF THE PROBLEM IS UPDATED BELOW:]
(addendum)
The only issue I am having is the code, as I am pretty much greenhorn in that department. I have been working to learn Visual Studio's workflow, but I really could use some help.
Thank you so much in advance for anything you can help me with.
UPDATE:
After doing research on the subject and taking time to do some thinking, I have come up with the code listed below; but my problem is that when I pan my image too far, the image is allowed to be pulled too far over, thus exposing the panel behind it when the image is panned/pulled too far over to one corner. Also, when I zoom too far out, the image is allowed to become WAY smaller than the Picturebox.
Panning issue, the grey parts of the panel are the problem
Zoom issue, the grey parts of the panel are the problem
So, my last question: How would I go about revising the code below to 'lock' the image that I am panning and zooming from being allowed to pan or zoom outside of its frame and expose the panel behind it?
public partial class ImageZoomMainForm : Form
{
Image img;
Point mouseDown;
int startx = 0;
int starty = 0;
int imgx = 0;
int imgy = 0;
bool mousepressed = false;
float zoom = 1;
public ImageZoomMainForm()
{
InitializeComponent();
string imagefilename = #"..\..\ViewPort_MAIN.tif";
img = Image.FromFile(imagefilename);
Graphics g = this.CreateGraphics();
zoom = ((float)pictureBox.Width / (float)img.Width) * (img.HorizontalResolution / g.DpiX);
pictureBox.Paint += new PaintEventHandler(imageBox_Paint);
}
private void pictureBox_MouseMove(object sender, EventArgs e)
{
MouseEventArgs mouse = e as MouseEventArgs;
if (mouse.Button == MouseButtons.Left)
{
Point mousePosNow = mouse.Location;
int deltaX = mousePosNow.X - mouseDown.X;
int deltaY = mousePosNow.Y - mouseDown.Y;
imgx = (int)(startx + (deltaX / zoom));
imgy = (int)(starty + (deltaY / zoom));
pictureBox.Refresh();
}
}
private void imageBox_MouseDown(object sender, EventArgs e)
{
MouseEventArgs mouse = e as MouseEventArgs;
if (mouse.Button == MouseButtons.Left)
{
if (!mousepressed)
{
mousepressed = true;
mouseDown = mouse.Location;
startx = imgx;
starty = imgy;
}
}
}
private void imageBox_MouseUp(object sender, EventArgs e)
{
mousepressed = false;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
float oldzoom = zoom;
if (e.Delta > 0)
{
zoom += 0.1F;
}
else if (e.Delta < 0)
{
zoom = Math.Max(zoom - 0.1F, 0.01F);
}
MouseEventArgs mouse = e as MouseEventArgs;
Point mousePosNow = mouse.Location;
int x = mousePosNow.X - pictureBox.Location.X;
int y = mousePosNow.Y - pictureBox.Location.Y;
int oldimagex = (int)(x / oldzoom);
int oldimagey = (int)(y / oldzoom);
int newimagex = (int)(x / zoom);
int newimagey = (int)(y / zoom);
imgx = newimagex - oldimagex + imgx;
imgy = newimagey - oldimagey + imgy;
pictureBox.Refresh();
}
private void imageBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.ScaleTransform(zoom, zoom);
e.Graphics.DrawImage(img, imgx, imgy);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
const int WM_SYSKEYDOWN = 0x104;
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch (keyData)
{
case Keys.Right:
imgx -= (int)(pictureBox.Width * 0.1F / zoom);
pictureBox.Refresh();
break;
case Keys.Left:
imgx += (int)(pictureBox.Width * 0.1F / zoom);
pictureBox.Refresh();
break;
case Keys.Down:
imgy -= (int)(pictureBox.Height * 0.1F / zoom);
pictureBox.Refresh();
break;
case Keys.Up:
imgy += (int)(pictureBox.Height * 0.1F / zoom);
pictureBox.Refresh();
break;
case Keys.PageDown:
imgy -= (int)(pictureBox.Height * 0.90F / zoom);
pictureBox.Refresh();
break;
case Keys.PageUp:
imgy += (int)(pictureBox.Height * 0.90F / zoom);
pictureBox.Refresh();
break;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void ImageZoomMainForm_Load(object sender, EventArgs e)
{
}
}
}
A picturebox inside a Panel,
the panel should be set its AutoSroll to True,
the picturebox with SizeMode to Zoom
the trackbar change can increase and decrease the size of inside picturebox so that the outer panel will have auto scroll
dragging also possible using several mouse events of the picturebox.

Form position on lower right corner of the screen

I am using c# WinForm to develop a sman notification app. I would like to place the main form on the lower right corner of the screen working area.
In case of multiple screens, there is a way to find the rightmost screen where to place the app, or at least remember the last used screen and palce the form on its lower right corner?
I don't currently have multiple displays to check, but it should be something like
public partial class LowerRightForm : Form
{
public LowerRightForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
PlaceLowerRight();
base.OnLoad(e);
}
private void PlaceLowerRight()
{
//Determine "rightmost" screen
Screen rightmost = Screen.AllScreens[0];
foreach (Screen screen in Screen.AllScreens)
{
if (screen.WorkingArea.Right > rightmost.WorkingArea.Right)
rightmost = screen;
}
this.Left = rightmost.WorkingArea.Right - this.Width;
this.Top = rightmost.WorkingArea.Bottom - this.Height;
}
}
Override the Form Onload and set the new location :
protected override void OnLoad(EventArgs e)
{
var screen = Screen.FromPoint(this.Location);
this.Location = new Point(screen.WorkingArea.Right - this.Width, screen.WorkingArea.Bottom - this.Height);
base.OnLoad(e);
}
//Get screen resolution
Rectangle res = Screen.PrimaryScreen.Bounds;
// Calculate location (etc. 1366 Width - form size...)
this.Location = new Point(res.Width - Size.Width, res.Height - Size.Height);
This following code should work :)
var rec = Screen.PrimaryScreen.WorkingArea;
int margain = 10;
this.Location = new Point(rec.Width - (this.Width + margain), rec.Height - (this.Height + margain));
int x = Screen.PrimaryScreen.WorkingArea.Right - this.Width;
int y = Screen.PrimaryScreen.WorkingArea.Bottom - this.Height;
// Add this for the real edge of the screen:
x = 0; // for Left Border or Get the screen Dimension to set it on the Right
this.Location = new Point(x, y);

How can I make a button take up its entire containing form?

I've made a floating button. I want it to take up the whole of the it's containing form but the below code has a margin between the right of the button and the right of the form.
public FloatButton()
{
InitializeComponents();
int width = (int)((double)Screen.PrimaryScreen.Bounds.Width / 20);
int height = (int)((double)Screen.PrimaryScreen.Bounds.Height / 20);
this.WindowState = FormWindowState.Normal;
FormBorderStyle = FormBorderStyle.None;
int x_pos = Screen.PrimaryScreen.Bounds.Width - width;
int y_pos = Screen.PrimaryScreen.Bounds.Height / 2 - height / 2;
this.Location = new Point(x_pos,y_pos);
this.Height = height;
this.Width = width;
this.button.Width = width;
this.button.Height = height;
}
EDIT: It's about 40 pixels and it doesn't change if I make the button text longer (the text wraps)
Does docking work for you?
this.button.Dock = System.Windows.Forms.DockStyle.Fill;
Just setting Dock to Fill should make the button fill up its parent's entire area.

Keeping a PictureBox centered inside a container

I am designing a simple picture viewer with ability to do some basic image processing. At the moment I have the problem of keeping the PictureBox centered inside a TabPage all the time as well as keeping the picturebox width and size same as the picture its showing. So far I had no success.
I have the following code that I call in form constructor to position it in center. it works the first time to center the picturebox:
private void SetPictureBoxOriginalSizeAndLocation(bool makeImageNull = false, DockStyle dockStyle = DockStyle.None)
{
if (makeImageNull) picBoxView.Image = null;
picBoxView.Dock = dockStyle;
var xPoint = tabImageView.Location.X + ((splitContainer.Panel2.Width / 2) / 2);
var yPoint = tabImageView.Location.Y;
var width = tabImageView.Width / 2;
var height = (tabImageView.Height / 2) - toolStripImageView.Height;
if (picBoxView.Image == null) return;
//Resize image according to width
picBoxView.Image = ImageMethods.ResizeImage(picBoxView.Image.Tag.ToString(), width, height, false);
picBoxView.Location = new Point(xPoint, yPoint);
picBoxView.Width = width;
picBoxView.Height = height;
}
But it does not resize the picturebox to its image (you can see the black part that is back color for the picturebox control):
The problem is getting worse as soon as I resize the form, the picturebox position will goes to top:
I call the code above in form's resize event as well, no idea why it works when application starts. Would be nice if someone can tell me what properties I should take care of to achieve a nicely centered picturebox which always is as big as its image.
It's pretty easy if you just set the Anchor style to none:
picBoxView = new PictureBox();
picBoxView.SizeMode = PictureBoxSizeMode.AutoSize;
picBoxView.Anchor = AnchorStyles.None;
tabImageView.Controls.Add(picBoxView);
CenterPictureBox(picBoxView, myImage);
Then just center the PictureBox initially whenever you change the image of the PictureBox:
private void CenterPictureBox(PictureBox picBox, Bitmap picImage) {
picBox.Image = picImage;
picBox.Location = new Point((picBox.Parent.ClientSize.Width / 2) - (picImage.Width / 2),
(picBox.Parent.ClientSize.Height / 2) - (picImage.Height / 2));
picBox.Refresh();
}
Having the Anchor = None will center the PictureBox control for you whenever the parent container gets resized because it "isn't" anchored to the default Left and Top locations.
Givien a Form with TabControl, which has Dock set to Fill, below will keep your PictureBox in the centre. It also sets PictureBox size to Bitmap size:
public partial class Form1 : Form
{
Bitmap b = new Bitmap(320, 200);
public Form1()
{
InitializeComponent();
CenterTheBox();
}
private void Form1_Resize(object sender, EventArgs e)
{
CenterTheBox();
}
void CenterTheBox()
{
pictureBox1.Size = b.Size;
var left = (tabPage1.ClientRectangle.Width - pictureBox1.ClientRectangle.Width) / 2;
var top = (tabPage1.ClientRectangle.Height - pictureBox1.ClientRectangle.Height) / 2;
pictureBox1.Location = new Point(tabPage1.ClientRectangle.Location.X + left, tabPage1.ClientRectangle.Location.Y + top);
}
}
I believe your problem lies here
var xPoint = tabImageView.Location.X + ((splitContainer.Panel2.Width / 2) / 2);
var yPoint = tabImageView.Location.Y;
var width = tabImageView.Width / 2;
var height = (tabImageView.Height / 2) - toolStripImageView.Height;
ypoint is alwways set to tabImageView Y, althought it should be set to
tabImageView.Location.Y + (tabImageView.Size.Height - picBoxView.Size.Height)/2
should be almost the same with xPoint
tabImageView.Location.X + (tabImageView.Size.Width - picBoxView.Size.Width)/2
and
width = picBoxView.Image.Width;
height = picBoxView.Image.Height;

How do I center a window on the screen in C# & WinForms?

I need a way to center the current window on the screen.
So for example, if a user pushes a button, I want the window to center itself on the screen.
I know you can use the startposition property, but I cannot figure out a way to use that other than when the application first starts up.
So how do I center the form on the screen?
Use Form.CenterToScreen() method.
Using the Property window
Select form → go to property window → select "start position" → select whatever the place you want.
Programmatically
Form form1 = new Form();
form1.StartPosition = FormStartPosition.CenterScreen;
form1.ShowDialog();
Note: Do not directly call Form.CenterToScreen() from your code. Read here.
A single line:
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
In Windows Forms:
this.StartPosition = FormStartPosition.CenterScreen;
In WPF:
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
That's all you have to do...
If you want to center your windows during runtime use the code below, copy it into your application:
protected void ReallyCenterToScreen()
{
Screen screen = Screen.FromControl(this);
Rectangle workingArea = screen.WorkingArea;
this.Location = new Point() {
X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}
And finally call the method above to get it working:
ReallyCenterToScreen();
Centering a form in runtime
1.Set following property of Form:
-> StartPosition : CenterScreen
-> WindowState: Normal
This will center the form at runtime but if form size is bigger then expected, do second step.
2. Add Custom Size after InitializeComponent();
public Form1()
{
InitializeComponent();
this.Size = new Size(800, 600);
}
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace centrewindow
{
public partial class Form1 : Form
{
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
[DllImport("user32.dll")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CentreWindow(Handle, GetMonitorDimensions());
}
private void CentreWindow(IntPtr handle, Size monitorDimensions)
{
RECT rect;
GetWindowRect(new HandleRef(this, handle), out rect);
var x1Pos = monitorDimensions.Width/2 - (rect.Right - rect.Left)/2;
var x2Pos = rect.Right - rect.Left;
var y1Pos = monitorDimensions.Height/2 - (rect.Bottom - rect.Top)/2;
var y2Pos = rect.Bottom - rect.Top;
SetWindowPos(handle, 0, x1Pos, y1Pos, x2Pos, y2Pos, 0);
}
private Size GetMonitorDimensions()
{
return SystemInformation.PrimaryMonitorSize;
}
}
}
Centers any window you can get the handle of
Use this:
this.CenterToScreen(); // This will take care of the current form
Might not be completely relevant to the question. But maybe can help someone.
Center Screen non of the above work for me. Reason was I was adding controls dynamically to the form. Technically when it centered it was correct , based on the form before adding the controls.
So here was my solution. ( Should work with both scenarios )
int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;
this.Location = new Point(x / 2, y / 2);
So you will notice that I am using "PreferredSize" instead of just using Height / Width.
The preferred size will hold the value of the form after adding the controls. Where Height / Width won't.
Hope this helps someone .
Cheers
Use Location property of the form. Set it to the desired top left point
desired x = (desktop_width - form_witdh)/2
desired y = (desktop_height - from_height)/2
Working sample
private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
AccountAddForm f = new AccountAddForm();
f.StartPosition = FormStartPosition.CenterScreen;
f.Show();
}
You can use the Screen.PrimaryScreen.Bounds to retrieve the size of the primary monitor (or inspect the Screen object to retrieve all monitors). Use those with MyForms.Bounds to figure out where to place your form.
In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:
// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;
// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;

Categories