EDIT: I've tried to solve this for over a week and I have searched here and elsewhere as well.
I'd like to begin with explaining that I am a hobby programmer and have nobody to ask for help. I can only read the books I buy and guides on the internet so I am sorry if the question is beyond stupid.
The case: I have a "Windows Form Application", the form itself is 500x500 in size and in it I have a "Picture Box"(size 400x400, loc 0,0).
I am aware that Thread.Sleep hangs the interface because it is not multi threaded.
The problem I suffer is that "OnPaint" is invoked when I launch the program.
If I add a button (dragged from the toolbox)then "OnPaint" is invoked TWO times and so on, confirmed up to 4 buttons. That is not the worst part however. Just mousing over the button (any button) invokes "OnPaint". As you can see, "Invalidate()" is not inserted yet because I can not even click the buttons yet.
How do I prevent this? What is the problem? What should I have done differently?
I mean, it does what I want just not when I want to.
Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
int radie = 25;
Random random = new Random();
Graphics graphics = pictureBox1.CreateGraphics();
Color color = Color.Black;
SolidBrush brush = new SolidBrush(color);
for (int i = 2500; i > 0; i--)
{
color = Color.FromArgb(random.Next(0, 101), random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
brush.Color = color;
graphics.FillEllipse(brush, random.Next(0, 400 - radie * 2), random.Next(0, 400 - radie * 2), radie * 2, radie * 2);
Thread.Sleep(1);
}
}
}
For those who wonder what it does it just fills the picture box with circles of different colors and opacity. edit: Its not filled instantly, its supposed to look "pretty".
Thanks in advance!
You could set the form's ControlStyle.
In the form .ctor or other appropriate startup event, add:
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
Related
I have created a custom ListView control to suit my needs and I'm having an issue that causes the ListView not to show any contents (not drawing anything, just white) when the form first loads.
If I resize the form or click on my control (anything that forces a repaint on the ListView) then it shows up as expected.
As a side note, it used to work just fine until I made a small change today and rebuilt the control. I removed all the changes I made and rebuilt again but the issue still happens. Any ideas as to why it will not show up (paint) when the form is first loaded?
This is what I use to do the custom drawing on my custom ListView control...
protected override void OnDrawItem(DrawListViewItemEventArgs e)
{
Image image = e.Item.ImageList.Images[e.Item.ImageIndex];
Size textSize = new Size((int)e.Graphics.MeasureString(e.Item.Text, e.Item.Font).Width, (int)e.Graphics.MeasureString(e.Item.Text, e.Item.Font).Height);
//Get the area of the item to be painted
Rectangle bounds = e.Bounds;
bounds.X = 0;
bounds.Width = this.Width;
//Set the spacing on the list view items
int hPadding = 0;
int vPadding = 0;
IntPtr padding = (IntPtr)(int)(((ushort)(hPadding + bounds.Width)) | (uint)((vPadding + bounds.Height) << 16));
SendMessage(this.Handle, (uint)ListViewMessage.LVM_SETICONSPACING, IntPtr.Zero, padding);
//Set the positions of the image and text
int imageLeft = (bounds.Width / 2) - (image.Width / 2);
int imageTop = bounds.Top + 3;
int textLeft = (bounds.Width / 2) - (textSize.Width / 2);
int textTop = imageTop + image.Height;
Point imagePosition = new Point(imageLeft, imageTop);
Point textPosition = new Point(textLeft, textTop);
//Draw background
using (Brush brush = new SolidBrush(e.Item.BackColor))
e.Graphics.FillRectangle(brush, bounds);
//Draw selected
if (e.Item.Selected)
{
using (Brush brush = new SolidBrush(m_SelectedColor))
e.Graphics.FillRectangle(brush, bounds);
}
//Draw image
e.Graphics.DrawImage(image, imagePosition);
//Draw text
e.Graphics.DrawString(e.Item.Text, e.Item.Font, new SolidBrush(e.Item.ForeColor), textPosition);
}
I also set the following things in the Constructor of my custom control...
public MyListView()
{
this.DoubleBuffered = true;
this.OwnerDraw = true;
this.View = View.LargeIcon;
this.Cursor = Cursors.Hand;
this.Scrollable = false;
}
I also inherit the ListView class...
public class MyListView : ListView
{
//All my source
}
You need to set the set the control to redraw itself when resized. So add this code in constructor of your control:
this.ResizeRedraw = true;
My apologies:
Doing the below reset my event handlers and the problem went away. However, once I hooked them up, I found the Resize event handler that I used to set the ColumnWidth was causing the issue. Why setting the ColumnWidth is causing this, I do not know.
Arvo Bowen's comment on this answer fixed it for me also (.NET 4.8 Framework, VS2022). To be clear, not requiring this.ResizeRedraw = true; from the answer.
So after much headache and time I found that I had absolutely nothing wrong with my control. It was your answer that made me create another control just like my existing one and test it. To my surprise it worked great. I simply copied my existing non-working control and pasted it on the form and then new one worked! Sometimes VS just does weird things... Somehow I managed to muck up the control's creation object or something..
Here is a class file I have for button creation:
class Button
{
Texture2D buttonTexture;
Rectangle buttonRectangle;
Color buttonColour = new Color(255, 255, 255, 255);
public Vector2 size, buttonPosition;
public Button(Texture2D newButtonTexture, Vector2 newSize)
{
buttonTexture = newButtonTexture;
size = newSize;
}
public void setPosition(Vector2 newButtonPosition)
{
buttonPosition = newButtonPosition;
}
bool down;
public bool isClicked;
public void Update(MouseState mouse)
{
buttonRectangle = new Rectangle((int)buttonPosition.X, (int)buttonPosition.Y, (int)size.X, (int)size.Y);
Rectangle mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);
if (mouseRectangle.Intersects(buttonRectangle))
{
if (buttonColour.A == 255)
down = false;
if (buttonColour.A == 0)
down = true;
if (down)
buttonColour.A += 3;
else
buttonColour.A -= 3;
if (mouse.LeftButton == ButtonState.Pressed)
isClicked = true;
}
else if (buttonColour.A < 255)
{
buttonColour.A += 3;
isClicked = false;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(buttonTexture, buttonRectangle, buttonColour);
}
}
Below is how I create the buttons in LoadContent (Ignore the shabby parameters it's just the way I'm currently doing it):
btnResume = new Button(Content.Load<Texture2D>("Buttons/button_Resume"), new Vector2(GraphicsDevice.Viewport.Width / 1.875f, GraphicsDevice.Viewport.Height / 4));
btnResume.setPosition(new Vector2(GraphicsDevice.Viewport.Width / 2 - (0.5f*btnResume.size.X), GraphicsDevice.Viewport.Height / 3));
btnQuit = new Button(Content.Load<Texture2D>("Buttons/button_Exit"), new Vector2(GraphicsDevice.Viewport.Width / 1.875f, GraphicsDevice.Viewport.Height / 4));
btnQuit.setPosition(new Vector2(GraphicsDevice.Viewport.Width / 2 - (0.5f*btnQuit.size.X), GraphicsDevice.Viewport.Height - (GraphicsDevice.Viewport.Height / 3)));
And this is how I draw the two buttons in the draw function of Game1.cs:
case GameState.Menu:
btnResume.Draw(spriteBatch);
btnQuit.Draw(spriteBatch);
break;
This all works fine. For some reason however, when doing the same thing for a "Play" button to put on a new game state called "MainMenu", the button doesn't show up (I have tested putting the button code in the game state "menu" and the button does appear, it just won't show when in any other game state other than "menu").
Does anybody know why it won't work? I've remembered to create the button, set the position, and then draw it within the "case GameState.MainMenu" part of the draw function in Game1.cs, so I honestly have no idea why it isn't working. As a side note, I've tried drawing buttons for another game state called "CharacterSelection" and that doesn't work either, HOWEVER it does work if I use spriteBatch.Draw (so I'm pretty sure it's a problem with the button class' draw function.
I can provide screenshots of code or in-game elements, and I'm sorry if the code is messy, I tend to do that a lot. This is my first XNA game and I've not coded in c# much in the past so a lot of this is new to me.
EDIT:
Here are all my gamestates:
enum GameState
{
Opening,
MainMenu,
CharacterSelection,
Countdown,
Playing,
Menu,
Options,
}
GameState CurrentGameState = GameState.Opening;
Opening - Opening cinematic Main Menu - Title Screen basically Character Selection - select what character to play as. Countdown - 3,2,1 GO before the game starts. Playing - Game is active, players are playing e.t.c Menu - Pause menu (opens when esc is pressed) Options - When "Options" is pressed in the pause or main menu (Hasn't been set up yet).
Thanks for the help, but I've solved it. Silly mistake by me! Forgot "btnPlay.Update(mouse);" in my update function! -__-
I am making a program where you bassicly move from tile to tile in windows forms.
So in order to do that, I wanted to use panels each panel has a tag. To detect collision.
So I have an image of my map. and I divided into multiple tiles. However now I have to drag 900 tiles onto panels.
This isn't very effective in 2 ways. First loading 900 textures isn't really a smart idea. Also it would take ages. So i wanted to use a spritesheet or tilemap. But how would I do that in winforms. I believe I have seen some people use a grid view or whatever. However im not sure how to do what I want to do.
What would be the best solution?
Thanks in advance!
For any serious gaming project WinForms is not the best platform. Either WPF or XNA or Unity are able to deliver high performance use of DirectX.
But since you want to do it in Winforms here is a way to do it.
It creates a whopping number of 900 PictureBoxes and loads each with a fraction of an source image:
private void Form1_Load(object sender, EventArgs e)
{
int tileWidth = 30;
int tileHeight = 30;
int tileRows = 30;
int tileCols = 30;
using (Bitmap sourceBmp = new Bitmap("D:\\900x900.jpg"))
{
Size s = new Size(tileWidth, tileHeight);
Rectangle destRect = new Rectangle(Point.Empty, s);
for (int row = 0; row < tileRows; row++)
for (int col = 0; col < tileCols; col++)
{
PictureBox p = new PictureBox();
p.Size = s;
Point loc = new Point(tileWidth * col, tileHeight * row);
Rectangle srcRect = new Rectangle(loc, s);
Bitmap tile = new Bitmap(tileWidth, tileHeight);
Graphics G = Graphics.FromImage(tile);
G.DrawImage(sourceBmp, destRect, srcRect, GraphicsUnit.Pixel);
p.Image = tile;
p.Location = loc;
p.Tag = loc;
p.Name = String.Format("Col={0:00}-Row={1:00}", col, row);
// p.MouseDown += p_MouseDown;
// p.MouseUp += p_MouseUp;
// p.MouseMove += p_MouseMove;
this.Controls.Add(p);
}
}
}
When I tried it I was a bit worried about perfomance, but..
This takes under 1 second to load on my machine.
Starting the programm adds 10MB to VS memory usage. That is like nothing.
For a fun project this will do; for best performance one might use Panels but these will have to be filled and refilled in the Paint event. This solution saves you the hassle and since you don't change the tile picture all the time this works well enough.
Pleae note: I have added a Name and a Tag to each PictureBox, so you can later refer to it. These both contain info about the original position of the Picturebox. The Name looks like this: Col=23-Row=02 and the Tag is the original Location object.
Also: Dynamically added controls take a little extra to script since you can't create their method bodies in the designer. Instead you add them like above. In doing so Intellisense and the Tab key are your best friends..
I have added three event handlers for a few mouse events. When you uncomment them you will have to add the methods like e.g. this:
void p_MouseMove(object sender, MouseEventArgs e)
{
throw new NotImplementedException();
}
But maybe you want to use other events to play like Drag&Drop or keyboard events..
There are two ways to refer to these tiles. Maybe you want to try and/or use both of them: You can loop over the form's controls with a
foreach (Control ctl in this.Controls)
{ if (ctl is PictureBox ) this.Text = ((PictureBox)ctl).Name ; }
It tests for the right type and then casts to PictureBox. As an example it displays the name of the tile in the window title.
Or you can have a variable and set it in the MouseDown event:
PictureBox currentTile;
void p_MouseDown(object sender, MouseEventArgs e)
{
currentTile = (PictureBox ) sender;
}
Ok, I'm having an issue that I'm not even sure exactly what is happening. Basically: I have a mouseup event for clicking on a button. That event will remove 1 button and physically move all the buttons on the screen to fill the gap. So if you have 2 rows of 2 buttons
Button1 Button2
Button3 Button4
and you click Button1, it moves the last 3 so you now have
Button2 Button3
Button4
Ok, so, at the end of this event handler it takes a screenshot and saves it (replacing the previous image of buttons 1-4 with the new image of buttons 2-4).
The event handler looks like this
public void Handle_Button_MouseUp(object sender, MouseEventArgs e)
{
//Get rid of the button that was clicked
...some unnecessary to the question code here...
//Rearrange the remaining buttons to fill the gap
Rearrange_Buttons_In_Tray(element);
//Save the screenshot
imageBox.Image = SavePanel1Screenshot();
}
The screenshot code is
public Image SavePanel1Screenshot()
{
int BorderWidth = (this.Width - this.ClientSize.Width) / 2;
int TitlebarHeight = this.Height - this.ClientSize.Height - BorderWidth;
Rectangle rect = new Rectangle(0, 0, panel1.Width, panel1.Height);
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(this.Left + panel1.Left + BorderWidth, this.Top + panel1.Top + TitlebarHeight, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
Image screenShot;
screenShot = (Image)bmp;
return screenShot;
}
.
public void Rearrange_Buttons_In_Tray(int element)
{
for (int i = element; i < buttonList.Count; i++)
{
Place_Button_In_Tray(buttonList[i].buttonSaved, i, true);
buttonList[i].element = i;
}
}
Cleaned out some unnecessary to the question parts to avoid clutter. Sorry for the messed up indentation. NOTE: The buttons are not IN the panel, just on top of it. I just use the panel for measurement and aesthetic purposes
private void Place_Button_In_Tray(Button button, int element, bool isReArrange)
{
button.Width = bigButtonWidth;
button.Height = bigButtonHeight;
Image buttonImage = button.Image;
int numButtonsHoriz = panel1.Width / button.Width;
int numButtonsVerti = panel1.Height / button.Height;
int extraSpaceHoriz = (panel1.Width % button.Width) / (numButtonsHoriz);
int extraSpaceVerti = (panel1.Height % button.Height) / numButtonsHoriz;
int buttonCount;
if (!isReArrange)
buttonCount = buttonList.Count - 1;
else
buttonCount = element;
if ((buttonCount) < numButtonsHoriz)
{
button.Location = new Point(panel1MinX + (button.Width * (buttonCount)) + extraSpaceHoriz, (panel1MinY + extraSpaceVerti));
}
else
{
int newLine = (buttonCount) % numButtonsHoriz;
button.Location = new Point(panel1MinX + (button.Width * (newLine)) + extraSpaceHoriz, ((panel1MinY + extraSpaceVerti) + (button.Height * ((buttonCount) / 2) - ((buttonCount) % 2))));
}
And now my problem: The image is of a blank screen. It's not that it isn't taking the picture- it's taking the picture before buttons 2-4 are visible on the screen (I can visibly see this happen as I step through the program. At the time the screenshot is taken, the screen is completely blank. Only after it takes do the buttons reappear on the screen)! For some reason, they are not rendering until AFTER the event handler is finished. Once the final piece of code in the event handler is done (the screenshot saving), the buttons all reappear in their respective spots, despite the fact that the visibility of the buttons is not modified at all during this entire process (thus they remain visible the entire time).
I'm a little confused as to what exactly is happening and, more importantly, how to go about getting that screenshot after the event handler takes place. >_> Does anyone have any suggestions on what might be going on and, more importantly, how to get that screenshot?
EDIT: My description is somewhat difficult to understand. I do apologize. It's hard to articulate exactly what I'm trying to do and what is happening. Here's a more compact and to the point version:
Basically, I'm only trying to hide 1 button out of 4. The other 3 on the screen are moved to new locations. For some reason, when they get moved, they vanish from the screen. They don't reappear until after the mouseup function completes, despite me never having modified whether they are visible or not. I only change their location. I want the screenshot to contain those 3 buttons, but for some reason they aren't popping back into existence until after the entire mouseup function ends. >_> So my screenshot is of an empty screen, devoid of buttons
It's a bit confusing what you are describing. I clicked a button to hide it, run your screen shot code, and the image did not show the button.
Anyway, to "delay" the screen shot to after the event is called, you can try using BeginInvoke:
this.BeginInvoke(new Action(() => { imageBox.Image = SavePanel1Screenshot(); }));
I think you need to call a Refresh after moving your controls:
if ((buttonCount) < numButtonsHoriz) {
button.Location = new Point(panel1MinX + (button.Width * (buttonCount)) + extraSpaceHoriz, (panel1MinY + extraSpaceVerti));
} else {
int newLine = (buttonCount) % numButtonsHoriz;
button.Location = new Point(panel1MinX + (button.Width * (newLine)) + extraSpaceHoriz, ((panel1MinY + extraSpaceVerti) + (button.Height * ((buttonCount) / 2) - ((buttonCount) % 2))));
}
panel1.Refresh();
You're doing your work in the UI thread. See How to force Buttons, TextBoxes to repaint on form after a MessageBox closes in C#. I'd suggest you move the screenshot to a background thread if you can.
You may also need to wait until the buttons have rendered, either using the blunt expedient of sleeping for 100ms or so, or by investigating the Paint event and using some sort of flag to indicate that both required events have occurred and the screenshot can be taken.
Alternatively, you could force it to redraw: How do I call paint event?
as long as you only need the pixels of your own form ...
private void button1_Click(object sender, EventArgs e)
{
//Button magic
button1.Visible = false;
button2.Location = button1.Location;
Bitmap bmp = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));
pictureBox1.Image = bmp;
//or do whatever you want with the bitmap
}
I have a userControl which has some programmatically drawn rectangles. I need few instances of that userControl on my form (see the image). The problem is that only the last instance will show the drawn shapes!
I guess it has something to do with drawing surface or the Paint event handler
In case it might help, here's some of the code I use in my control:
private void MyUserControl_Paint(object sender, PaintEventArgs e)
{
showHoraireMaitresse();
Rectangle rec = showDisponibilités();
var b = new SolidBrush(Color.FromArgb(150, Color.Blue));
e.Graphics.FillRectangle (b, rec);
showOccupation();
}
private void showHoraireMaitresse()
{
heureDebut = 8;
for (int i = 0; i < 14; i++)
{
//Label d'heure -> This shows just fine
addLabel(i, heureDebut);
//Rectangles d'heure -> This shows only in last instance
var rectangle = new Rectangle(180 + i * largeurDUneHeure, 14, largeurDUneHeure, 30);
surface.DrawRectangle(defaultPen, rectangle);
}
addLabel(14, heureDebut);
}
Thank you!
Without further information, I'm going to guess that 'surface' is static.
Trace through OnPaint and check which control is painting, and what the bounds are for 'surface'. Perhaps all the controls are painting the same exact rectangle.