FontDialog类继承自CommonDialog,没有Location及Size属性,其他自CommonDialog派生的类,如ColorDialog、FileDialog等也是如此。
API函数GetWindowRect、SetWindowPos可以获取和设置窗体的位置和大小。
1
using System;
2
using System.Drawing;
3
using System.Windows.Forms;
4
using System.Runtime.InteropServices;
5
6
class FontDialog : System.Windows.Forms.FontDialog
7

{
8
public int Left
{ get
{ return r.Left ; } set
{ r.Left = value; } }
9
public int Top
{ get
{ return r.Top ; } set
{ r.Top = value; } }
10
public int Width
{ get
{ return r.Width ; } set
{ r.Width = value; } }
11
public int Height
{ get
{ return r.Height ; } set
{ r.Height = value; } }
12
public Point Location
{ get
{ return r.Location; } set
{ r.Location = value; } }
13
public Size Size
{ get
{ return r.Size ; } }
14
15
Rect r;
16
17
const uint SWP_NOSIZE = 1;
18
const uint SWP_NOZORDER = 4;
19
20
[DllImport("user32.dll")]
21
static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
22
23
[DllImport("user32.dll")]
24
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
25
26
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
27
protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
28
{
29
SetWindowPos(hWnd, (IntPtr)0, Left, Top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
30
GetWindowRect(hWnd, ref r);
31
return base.HookProc(hWnd, msg, wParam, lParam);
32
}
33
}
34
35
class Form1 : Form
36

{
37
Form1()
38
{
39
Button btn = new Button();
40
btn.Parent = this;
41
btn.Text = "&Font";
42
btn.Click += delegate
43
{
44
FontDialog fd = new FontDialog();
45
fd.Location = new Point(10, 50);
46
fd.ShowDialog();
47
};
48
}
49
50
static void Main()
51
{
52
Application.Run(new Form1());
53
}
54
}
55
56
[StructLayout(LayoutKind.Sequential)]
57
public struct Rect
58

{
59
public int Left;
60
public int Top;
61
public int Right;
62
public int Bottom;
63
64
public int Width
{ get
{ return Right - Left; } set
{ Right = Left + value; } }
65
public int Height
{ get
{ return Bottom - Top; } set
{ Bottom = Top + value; } }
66
67
public Size Size
68
{
69
get
{ return new Size(Width, Height); }
70
set
{ Width = value.Width; Height = value.Height; }
71
}
72
73
public Point Location
74
{
75
get
{ return new Point(Left, Top); }
76
set
{ Right -= (Left - value.X); Bottom -= (Bottom - value.Y); Left = value.X; Top = value.Y; }
77
}
78
79
public override string ToString()
80
{
81
return string.Format("{{X={0},Y={1},Width={2},Height={3}}}", Left, Top, Width, Height);
82
}
83
}
84