Implementation code in C to make the control display in full screen (WinForm)

  • 2020-05-07 20:16:04
  • OfStack

1. Use winapi "SetParent" interface:
 
[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); 

After executing the above code, our control has been able to display in full screen, but there is still a small problem, we should provide another function, let the user press a certain key, exit in full screen, otherwise can not be turned off, who are more depressed to use. At this point you should add an event to the control, fetch the key, and return. Let's take the Esc key as an example:
 
private void AddEventKeyUp(Control control) { 
if (control != null) { 
control.KeyUp += new KeyEventHandler(control_KeyUp); 
foreach (Control c in control.Controls) {//  You need to add child controls as well, or you may not get them.  
AddEventKeyUp(c); 
} 
} 
} 
void control_KeyUp(object sender, KeyEventArgs e) { 
if (e.KeyCode == Keys.Escape) { 
if (control != null) { 
SetParent(control.Handle,  The original parent.Handle); 
control.Dock = DockStyle.Fill; 
} 
} 
} 

The modified code is as follows:
 
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();//  Get focus, or you won't get a button  
SetParent(control.Handle, IntPtr.Zero); 

2. Create a new window and set FormBorderStyle to None, WindowState to Maximized, TopMost to True. Then the specific code is as follows:
 
AddEventKeyUp(control); 
 The original 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(); 
 The original parent.Controls.Add(control);//  This can't be the same as this Close The order is wrong, otherwise it will cause an error, because Close After the control is destroyed.  
frm.Close(); 
frm = null; 
} 
} 
} 
} 

After practical use, the second method is very good, without any problems. I just need to open one more window. The first method has a slight problem, that is, if there is a right-click menu or something on the control, the 1 call will go to the main interface. The mouse doesn't seem to work well sometimes.
Author: xia rongquan
E-mail: lyout (at) 163. com

Related articles: