我有一個表格Form1
,並帶有一個可創建其他表格的按鈕。但是,我只想一次創建1個附加表單。以下是我的代碼實現以下。我試圖使用Focus
屬性,但它不起作用。C#防止創建其他表格
private void addLocation(object sender, MouseClickEventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
form2.Focus();
}
我有一個表格Form1
,並帶有一個可創建其他表格的按鈕。但是,我只想一次創建1個附加表單。以下是我的代碼實現以下。我試圖使用Focus
屬性,但它不起作用。C#防止創建其他表格
private void addLocation(object sender, MouseClickEventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
form2.Focus();
}
使用Application.OpenForms
集合來檢查您是否已經打開了該窗體的實例。
private void addLocation(object sender, MouseClickEventArgs e)
{
Form2 form2 = Application.OpenForms.OfType<Form2>().SingleOrDefault();
if(form2 == null)
{
form2 = new Form2();
form2.Show();
form2.Focus();
}
}
您可以點擊按鈕改變光標然後還原代碼之後創建的形式完成或形式,它自
// Set cursor as hourglass
Cursor.Current =光標禁用用戶.WaitCursor;
//這裏,可執行的時間密集型的散列碼...
//設置光標默認箭頭 Cursor.Current = Cursors.Default;
所以,如果形式打開了它應該被帶到前面和重點(顯示仿真),如果沒有則打開創建和顯示:
// If there're many instances, let's take the last one
Form2 form = Application.OpenForms
.OfType<Form2>()
.LastOrDefault();
if (null == form) {
form = new From2();
form.Show();
}
else {
// Show emulation:
// - we don't want minimized window,
// - window should be at front
// - window should have a keyboard focus
if (form.WindowState == FormWindowState.Minimized)
form.WindowState = FormWindowState.Normal;
form.BringToFront();
if (form.CanFocus)
form.Focus();
}