I have the below code to draw a button(s) onto a panel for each monitor that is currently connected to the PC.
var padding = 5;
var buttonSize = new Size(95, 75);
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
var screen = Screen.AllScreens[i];
Button monitor = new Button
{
Name = "Monitor" + screen,
AutoSize = true,
Size = buttonSize,
Location = new Point(12 + i * (buttonSize.Width + padding), 14),
BackgroundImageLayout = ImageLayout.Stretch,
BackgroundImage = Properties.Resources.display_enabled,
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.White,
BackColor = Color.Transparent,
Text = screen.Bounds.Width + "x" + screen.Bounds.Height
};
monitorPanel.Controls.Add(monitor);
}
For devices with one or more monitors attached, the code works just fine and this is the end result:
However, while it works, I'd like to (if possible) order them as they appear in the Windows display view:
In the first screenshot, they are ordered as 2 | 3 | 1 instead of 3 | 2 | 1.
Is what I'm after possible?
Multiple screens in Windows are handled as one, big, "glued" working area. Based on that, order of screens in configuration is according to their position in the new working area. Assuming that all of your screens are in one line, you can just use
screen.Bounds.X
as ordering property. If the screens are layed out in multiple rows, then ordering will also have to consider Y component.
EDIT:
You could just use Linq for sorting, specifically OrderBy().
Example usage for case when screens are in one row and collection will be iterated once.
Change
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
var screen = Screen.AllScreens[i];
to
foreach(var screen in Screen.AllScreens.OrderBy(i => i.Bounds.X))
{
Related
I create a contact manager. The user can already enter some and they are stored in a file and re-opened when the program is started. Each contact is an object of my Person class.
When launching the program (in Load()) I created a for loop until all contacts have been explored (contacts are stored when opened in a Person table)
So now I come to my problem:
I have a panel that is scrollable (I have enabled the option) and I would like every 50 pixels in height, that a new panel is created with name, first name, email and phone number of my contacts and a pictureBox.
Except, I would like to be able to do it dynamically instead of creating the same thing more than 50 times and repeating the same code 50 times
Because for the moment I have done this:
for(int i = 0; i < contacts.Count; i++) //Afficher les contacts
{
if(!panel_contact1.Visible)
{
panel_contact1.Visible = true;
label_prenom_nom1.Text = contacts[i].Prenom + " " + contacts[i].Nom;
label_email1.Text = contacts[i].mail;
label_tel1.Text = contacts[i].tel;
pictureBox1.Image = Image.FromFile(contacts[i].pathImage);
}
else if(!panel_contact2.Visible)
{
panel_contact2.Visible = true;
label_prenom_nom2.Text = contacts[i].Prenom + " " + contacts[i].Nom;
label_email2.Text = contacts[i].mail;
label_tel2.Text = contacts[i].tel;
pictureBox2.Image = Image.FromFile(contacts[i].pathImage);
}
}
It's the code only for the first two contacts and I don't want to repeat it up to 100 times.
So my question is:
How to create panels, with in each of the labels and a pictureBox, every 50px in a panel.
Thank you for reading, if you just have advice said always the same if you all have the code I'm a taker especially since I think it should be easy to do because the content of the labels are already dynamically teaching.
Thank you.
On WinForms, you can use this:
int x = 0;
int y = 0;
int delta = 10;
for ( int i = 0; i < contacts.Count; i++ )
{
// Create picture box
var picture = new PictureBox();
picture.Image = Image.FromFile(contacts[i].pathImage);
picture.Location = new Point(x, y);
picture.Size = new Size(picture.Image.Width, picture.Image.Height);
int dx = picture.Width + delta;
// Create name label
var labelName = new Label();
labelName.AutoSize = true;
labelName.Location = new Point(x + dx, y);
labelName.Font = new Font(labelName.Font, FontStyle.Bold);
labelName.Text = contacts[i].Prenom + " " + contacts[i].Nom;
// Create mail label
var labelMail = new Label();
labelMail.AutoSize = true;
labelMail.Location = new Point(x + dx, y + labelName.Height);
labelMail.Text = contacts[i].mail;
// Create phone label
var labelPhone = new Label();
labelPhone.AutoSize = true;
labelPhone.Location = new Point(x + dx, y + labelName.Height + labelMail.Height);
labelPhone.Text = contacts[i].tel;
// Add controls
panel.Controls.Add(picture);
panel.Controls.Add(labelName);
panel.Controls.Add(labelMail);
panel.Controls.Add(labelPhone);
// Iterate
int dy1 = labelName.Height + labelMail.Height + labelPhone.Height;
int dy2 = picture.Height;
y += Math.Max(dy1, dy2) + delta;
}
But you may prefer create a custom control where you put a picture box and three labels designed as you want with colors, font size, bolding, margin, borderstyle and so on, with Height at 50.
Add new user custom control with Project > Add > User control and choose a file name like PersonControl.
public partial class PersonControl : UserControl
{
public PersonControl()
{
InitializeComponent();
}
public PersonControl(Person person) : this()
{
pictureBox.Image = Image.FromFile(person.pathImage);
labelName.Text = person.Prenom + " " + person.Nom;
labelMail.Text = person.mail;
labelPhone.Text = person.tel;
}
}
int x = 0;
int y = 0;
for ( int i = 0; i < contacts.Count; i++ )
{
var control = new PersonControl(contacts[i]);
control.Location = new Point(x, y);
panel.Controls.Add(control);
y += control.Height;
}
You should take care of the file image size that must be the same for all and the same as the picture box else you need to manage that by resizing for example.
How to resize an Image C#
If you're using windows forms, create a user control with a constructor using the Person object, set the labels and picture boxes to the info of that person. In the main loop you posted, create a new instance of this and set it's position to 0, i * 50 to place it under the previous one.
Example:
for(int i = 0; i < contacts.Count; i++)
{
YourUserControl u1 = new YourUserControl(pass the person object);
Panel1.Controls.Add(u1);
u1.Location = new Point(0, i * 50);
}
This depends on the display technolgy you are using (WinForms, WPF/UWP, ASP.NET, other).
In Windows Forms you just create the elements and add them to the container. The designer wroks on it's own part of the partial class. The designer code is run with InitializeComponents() in the constructor. Anything it can do, you can do. And you can easily look at it.
In WPF/UWP stuff is a bit more complicated. The designer does not work on code, but on XAML, a dedciated markup language. You are not supposed to manually add anything to the UI from the code. WPF/UWP and XAML were designed with the MVVM pattern in mind. And dealing with lists of things is what it does best. While you can use other patterns, generally that looses 90% of it's power and runs into issues at every other corner.
For ASP.Net it would depend on wich pattern you use. While not originally designed for it, MVC has been extremely popular with WebApplication. So much so, it is almost synonimous with WebApplications and ASP.NET. However this does not look like a web Application.
I have a Windows form where I am adding a button control for each monitor attached to a computer. Naturally as the number of displays very from PC to PC, I want to automatically add a button per display and add them so they are displayed in a row.
Currently my code is as so:
foreach (var screen in Screen.AllScreens)
{
Button monitor = new Button
{
Name = "Monitor" + screen,
AutoSize = true,
Size = new Size(100, 60),
Location = new Point(12, 70),
ImageAlign = ContentAlignment.MiddleCenter,
Image = Properties.Resources.display_enabled,
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.White,
BackColor = Color.Transparent,
Text = screen.Bounds.Width + "x" + screen.Bounds.Height
};
monitorPanel.Controls.Add(monitor);
}
This is working however, it's simply placing each button on top of each other where there is more than one display (as I expected it would):
What I want to achieve is that each button is added, but in a row next to each other. I've tried various threads, searches on Google etc to no avail. Could anyone point me in the right direction please?
IIRC AllScreens can be indexed, so:
var padding = 5;
var buttonSize = new Size(100, 60);
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
var screen = Screen.AllScreens[i];
Button monitor = new Button
{
Name = "Monitor" + screen,
AutoSize = true,
Size = buttonSize,
Location = new Point(12 + i * (buttonSize.Width + padding), 70),
ImageAlign = ContentAlignment.MiddleCenter,
Image = Properties.Resources.display_enabled,
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.White,
BackColor = Color.Transparent,
Text = screen.Bounds.Width + "x" + screen.Bounds.Height
};
monitorPanel.Controls.Add(monitor);
}
That ought to do it.
Advantages of this over the other answers: counter/indexer is built into the loop.
I couldn't try but shouldn't you set the Location different per button?
Location = new Point(12, 70),
to e.g.
Location = new Point(12 + (100 + gap) * screen_index, 70),
where 100 is the width of the screen
gap is the gap between two screens
and screen_index the index from left to right
You are in control of setting the position. You are actually setting it yourself:
Size = new Size(100, 60),
Location = new Point(12, 70)
I'd suggest you increase location with the size of each button, and additional padding:
Location = new Point(screenNumber * (100 + 5), 70)
Or something. Of course screenNumber is a counter you have to declare, initialize and increment upon each iteration.
I want to add text(say, annotations) in MS chart(winforms) like (10, 20) , (30, 40) where I already have a scroll bar.
I can able to draw strings(graphics.drawstring) in Chart, but on scrolling the horizontal scroll bar, the text which I have drawn remains static and immovable.
On scrolling the scrollbar, the text which I have drawn also should move along with my horizontal scrolling.
My code follows:
chart2.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
chart2.BorderlineColor = System.Drawing.Color.FromArgb(26, 59, 105);
chart2.BorderlineWidth = 3;
chart2.BackColor = Color.White;
chart2.ChartAreas.Add("chtArea");
chart2.ChartAreas[0].AxisX.Title = "Category Name";
chart2.ChartAreas[0].AxisX.TitleFont =
new System.Drawing.Font("Verdana", 11, System.Drawing.FontStyle.Bold);
chart2.ChartAreas[0].AxisY.Title = "UnitPrice";
chart2.ChartAreas[0].AxisY.TitleFont =
new System.Drawing.Font("Verdana", 11, System.Drawing.FontStyle.Bold);
chart2.ChartAreas[0].BorderDashStyle = ChartDashStyle.Solid;
chart2.ChartAreas[0].BorderWidth = 2;
chart2.ChartAreas["chtArea"].AxisX.ScrollBar.Enabled = true;
chart2.ChartAreas["chtArea"].CursorX.IsUserEnabled = true;
chart2.ChartAreas["chtArea"].CursorX.IsUserSelectionEnabled = true;
chart2.ChartAreas["chtArea"].AxisX.ScaleView.Zoomable = false;
chart2.ChartAreas["chtArea"].AxisX.ScrollBar.IsPositionedInside = true;
chart2.ChartAreas["chtArea"].AxisX.ScaleView.Size = 20;
chart2.ChartAreas[0].AxisX.ScaleView.SmallScrollSizeType = DateTimeIntervalType.Seconds;
chart2.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = 1;
chart2.Legends.Add("UnitPrice");
chart2.Series.Add("UnitPrice");
chart2.Series[0].ChartType = SeriesChartType.Line;
Random rand = new Random();
var valuesArray = Enumerable.Range(0, 500).Select(x => rand.Next(0, 100)).ToArray();
for (int i = 0; i < 500; i++)
{
chart2.Series["UnitPrice"].Points.AddXY(i+10, valuesArray[i]);
}
I tried TextAnnotaions, Line annotations, etc Nothing helped me.
Then I tried drawing dynamic labels inside MS chart also. Labels remain immovable while scrolling horizontal scroll bar.
This code works perfectly in your machine also.
Sounds a lot as if you want to add TextAnnotations.
If you want them to stick with your data points you should anchor them to the points they shall stay with.
Here are a few examples:
// directly anchored to a point
TextAnnotation TA1 = new TextAnnotation();
TA1.Text = "DataPoint 222";
TA1.SetAnchor(chart2.Series["UnitPrice"].Points[222]);
chart2.Annotations.Add(TA1);
// anchored to a point but shifted down
TextAnnotation TA2 = new TextAnnotation();
TA2.Text = "DataPoint 111";
TA2.AnchorDataPoint = chart2.Series["UnitPrice"].Points[111];
TA2.AnchorY = 0;
chart2.Annotations.Add(TA2);
// this one is not anchored on a point:
TextAnnotation TA3 = new TextAnnotation();
TA3.Text = "At 50% width BC";
TA3.AnchorX = 50; // 50% of chart width
TA3.AnchorY = 20; // 20% of chart height, from top!
TA3.Alignment = ContentAlignment.BottomCenter; // try a few!
chart2.Annotations.Add(TA3);
By default they either anchor to DataPoints or are positioned in % of the chart size.
It is also possible to set the positions according to pixel coordinates, but for this you need to calculate the positions each time the chart changes its view!
See here for an example how to transform chart data positions to chart control coordinates and vice versa.. (Not really recommended, though)
Background
I have a tab which is made active if there is more than one record returned from a query on my database.
For each record returned I would like a set of labels created and placed on the tab. For example if there are 8 records I would like 8 labels created.
Question
My loop only creates one label, even though my count is showing I have 8 records? Not sure why?
How do you create labels in a loop 8 times and not have them draw in the same location 8 times? I would them to appear in a horizontal list. Pretty sure the way I have coded the solution ,they will all be drawn in the same place?
Code
for (int i = 1; i <= rowCount; i++)
{
// Create objects
LinkLabel Linklabel1 = new LinkLabel();
Linklabel1.Text += ds.Tables[0].Rows[0]["code"].ToString();
Linklabel1.Location = new Point(10, 50);
Linklabel1.Height = 40;
Linklabel1.Width = 100;
tabControl1.TabPages[0].Controls.Add(Linklabel1);
}
Try something like this out:
for (int i = 0; i < rowCount; i++)
{
// Create objects
LinkLabel Linklabel1 = new LinkLabel();
Linklabel1.Text = ds.Tables[0].Rows[i]["code"].ToString();
Linklabel1.Height = 40;
Linklabel1.Width = 100;
Linklabel1.Location = new Point((i + 1) * 10 + (i * Linklabel1.Width), 50);
tabControl1.TabPages[0].Controls.Add(Linklabel1);
}
If you don't want to explicitly position them by setting the Location() property, consider putting a FlowLayoutPanel on the TabPage and added the controls to that instead. Then they will positioned automatically for you.
I have a windows forms application written in c#. I create checkboxes, textboxes and buttons in a panel. I have some problems when I run it in the rectangle monitor.
If I make the computer font size normal (control panel -> Appearance and Themes), there is no problem. Textbox and button alignment is top right and it works.
But when I change the computer font to larger from control panel textboxes and buttons go left. Alignments don't work. By the way I created all in run time. I use this code:
tmin[i].Anchor = AnchorStyles.Right | AnchorStyles.Top;
tmax[i].Anchor = AnchorStyles.Right | AnchorStyles.Top;
gb[i].Anchor = AnchorStyles.Right | AnchorStyles.Top;
tmin and tmax are arrays of textboxes. gb is array of button. what can I do about this?
EDIT
For example initiliazation of tmax textbox array is :
height = 1;
padding = 10;
for (int i = 3; i < ff.documentColumnCount; i++)
{
tmax[i] = new TextBox();
tmax[i].Name = max + (i - 2).ToString();
tmax[i].TabIndex = i;
tmax[i].Size = new System.Drawing.Size(65, 20);
tmax[i].Location = new System.Drawing.Point(326, 36 + i * 20);
tmax[i].TextChanged += new System.EventHandler(tmax17_TextChanged);
tmax[i].Bounds = new Rectangle(326, 20 + padding + height, 65, 22);
tmax[i].Anchor = AnchorStyles.Right | AnchorStyles.Top;
maxTextBoxes.Add(tmax[i]);
panel5.Controls.Add(tmax[i]);
height += 22;
}
Don't use anchors. Using Dock property instead, and set Min size as needed.
Instead of anchoring the control to the right edge of the form (which is what AnchorStyles.Right means), set the TextAlign property to HorizontalAlignment.Right, so that the text within the control is right-aligned.