Introduction
There's no method in C# to position a MessageBox. But in C++, you can position a message box by finding the message box and moving it. In this tip, I'll tell you how to position a MessageBox in C#.
Using the Code
At the top of your code file, add these using namespace statements:
using System.Runtime.InteropServices;
using System.Threading;
In your Form class, add these DllImport attributes:
[DllImport("user32.dll")]
static extern IntPtr FindWindow(IntPtr classname, string title);
[DllImport("user32.dll")]
static extern void MoveWindow(IntPtr hwnd, int X, int Y,
int nWidth, int nHeight, bool rePaint);
[DllImport("user32.dll")]
static extern bool GetWindowRect
(IntPtr hwnd, out Rectangle rect);
The DllImportAttribute class is available in each .NET version.
Then, you need to find and move the MessageBox. To do that, use this code:
void FindAndMoveMsgBox(int x, int y, bool repaint, string title)
{
Thread thr = new Thread(() => {
IntPtr msgBox = IntPtr.Zero;
while ((msgBox = FindWindow(IntPtr.Zero, title)) == IntPtr.Zero) ;
Rectangle r = new Rectangle();
GetWindowRect(msgBox, out r); MoveWindow(msgBox , x , y,
r.Width - r.X ,
r.Height - r.Y ,
repaint );
});
thr.Start(); }
Call this method before you call MessageBox.Show. When you call MessageBox.Show, be sure the caption parameter isn't empty, because the title parameter must be equal to the caption parameter.
For example:
FindAndMoveMsgBox(0, 0, true,"Title");
MessageBox.Show("Message","Title");