Showing a form or dialog at a random location

As I wait in dreadful silence to find out whether or not this company will stay in business (and hence whether all of us will be retrenched), I find myself blogging obsessively… the value of these posts is rather dubious, I fear.

Again, the source, for this and a whole bunch of other stuff, is here:

My pet project written completely in my spare time… how many more posts can I possibly squeeze out of it?

Anyway, it always pissed me off that setting a form’s startup type as WindowsDefaultLocation in c# causes all forms of that type to start up in exactly the same place. e.g. My application supports multiple simultaneous similar operations, like converting videos, or creating zip files, that show modeless progress dialogs. I don’t want all of those dialogs on top of each other. Thus I added this silly method to my base form class (Called from OnLoad when required):

  1. /// <summary>Sets the form’s location to a random point on the screen.</summary><remarks>
  2. /// This was added because in .Net, when a form’s StartPosition is set to WindowsDefaultLocation,
  3. /// all instances (of that type) will start at the same location. This allows each instance to
  4. /// start at a different pseudo-random location.</remarks>
  5. protected virtual void SetRandomLocation()
  6. {
  7.     const int screenPadding = 80;
  8.     var currentScreen = Screen.FromControl(this);
  9.     var maxLeft = currentScreen.Bounds.Left + currentScreen.Bounds.Width – Width – screenPadding;
  10.     var maxTop = currentScreen.Bounds.Top + currentScreen.Bounds.Height – Height – screenPadding;
  11.     var random = new Random();
  13.     Location = new Point(random.Next(currentScreen.Bounds.Left + screenPadding, maxLeft), random.Next(currentScreen.Bounds.Top + screenPadding, maxTop));
  14. }


Depending on how many monitors there are, and the circumstances of the form or dialog being created, the above code may not be ideal. Thus I made it a virtual method. In fact, I did override it somewhere, but I don’t recall the details of why right now.



About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s