[英]How Do I invoke/call a button click event handler form another handler? (c# )
[英]C# How do I create code to set a form back to default properties, with a button click event?
使用Visual C#2008快速版,我試圖在我的表單上創建一個按鈕,將表單設置回默認屬性,如大小,背景顏色等等......任何人都有關於我如何做這個的任何例子?
對於每個屬性信息,您可以獲取DefaultValueAttribute並將所需的Property設置為其值。
如果不在某處保存原始狀態,則無法執行此操作。
只需創建一個包含默認信息的類:
class DefaultFormInfo
{
int Width { get; set; }
int Height { get; set; }
}
然后用一些反思:
static DefaultFormInfo FormInfo = new DefaultFormInfo();
void FillDefaults()
{
foreach (PropertyInfo pinf in FormInfo.GetType().GetProperties())
{
pinf.SetValue(FormInfo, this.GetType().GetProperty(pinf.Name).GetValue(this, null), null);
}
}
void Restore()
{
foreach (PropertyInfo pinf in FormInfo.GetType().GetProperties())
{
this.GetType().GetProperty(pinf.Name).SetValue(this, pinf.GetValue(FormInfo, null), null);
}
}
到目前為止,最簡單的方法是創建表單的新實例並關閉舊表單。 如果這是你的應用程序的主要形式,這需要一些手術,關閉它將終止程序。 首先打開Program.cs並編輯它,看起來像這樣:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppContext = new ApplicationContext();
AppContext.MainForm = new Form1();
Application.Run(AppContext);
}
public static ApplicationContext AppContext;
}
ApplicationContext變量現在控制應用程序的生命周期,而不是Form1實例。 您可以使用Form1中的代碼重新創建表單:
private void button1_Click(object sender, EventArgs e) {
Form1 frm = new Form1();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = this.Location;
frm.Size = this.Size;
Program.AppContext.MainForm = frm;
frm.Show();
this.Close();
}
最簡單的解決方案可能是定義一些表單級別變量,並在事件中記錄默認值,如Form Load事件:
// form scoped variables
private Color defaultBackColor;
private Rectangle defaultBounds;
private FormWindowState defaultFormWindowState;
// save the Form default Color, Bounds, FormWindowState
private void Form1_Load(object sender, EventArgs e)
{
defaultBackColor = this.BackColor;
defaultBounds = this.Bounds;
defaultFormWindowState = this.WindowState;
}
然后在按鈕的Click事件中:重置默認值:
// restore the defaults on Button click
private void btn_FormReset_Click(object sender, EventArgs e)
{
this.WindowState = defaultFormWindowState;
this.Bounds = defaultBounds;
this.BackColor = defaultBackColor;
}
有一些更強大的方法可以實現這一點,包括使用Visual Studio的“設置”功能(在設計時和運行時):在以下位置查看它們:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.