1.应用winapi “SetParent” 接口:
[DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
control.Dock = DockStyle.None; control.Left = 0; control.Top = 0; control.Width = Screen.PrimaryScreen.Bounds.Width; control.Height = Screen.PrimaryScreen.WorkingArea.Height; SetParent(control.Handle, IntPtr.Zero);
履行上方的代码后,我们的 control已经可以全屏显示了,但还有一个小题目,我们应当再供给一个功能,让用户按某个键后,退出全屏,要不然关不掉,给谁用都斗劲愁闷。这个时辰应当给控件添加相干事务,取到键后返回。我们以Esc键为例:
private void AddEventKeyUp(Control control) { if (control != null) { control.KeyUp += new KeyEventHandler(control_KeyUp); foreach (Control c in control.Controls) {// 须要给子控件也添加上,不然有可能取不到。 AddEventKeyUp(c); } } } void control_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { if (control != null) { SetParent(control.Handle, 本来的parent.Handle); control.Dock = DockStyle.Fill; } } }
批改后的代码如下:
control.Dock = DockStyle.None; control.Left = 0; control.Top = 0; control.Width = Screen.PrimaryScreen.Bounds.Width; control.Height = Screen.PrimaryScreen.WorkingArea.Height; AddEventKeyUp(control); control.Focus();// 获得核心,不然也得不到按键 SetParent(control.Handle, IntPtr.Zero);
2.新建一个窗口,设置 FormBorderStyle为None,WindowState为Maximized,TopMost为True。然后具体代码如下:
AddEventKeyUp(control); 本来的parent.Controls.Clear(); frmFullscreen frm = new frmFullscreen(); frm.Controls.Add(control); frm.ShowDialog();
private void AddEventKeyUp(Control control) { if (control != null) { control.KeyUp += new KeyEventHandler(control_KeyUp); foreach (Control c in control.Controls) { AddEventKeyUp(c); } } } void control_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { if (control != null) { if (frm != null) { frm.Controls.Clear(); 本来的parent.Controls.Add(control);// 这里不克不及和下面的Close次序错了,要不然会引起错误,因为Close后把控件烧毁了。 frm.Close(); frm = null; } } } }