Windows.Forms Visual Studio, как открыть второе окно прямо над первым окном?

2

Как открыть второе окно непосредственно над первым, а не слегка по диагонали вниз или вправо по умолчанию? Я просто пытаюсь сделать несколько экранов, которые нужно щелкнуть. Есть ли другой способ, которым я должен это делать?

почему это делает CenterParent? Что делает CenterParent?

  • 0
    Центр родителя работает, когда вы назначаете родителя второй формы. Вы можете сделать это в конструкторе второй формы.
  • 0
    Аналогичный вопрос: stackoverflow.com/questions/944897/…
Теги:
winforms
visual-studio-2008

2 ответа

2
Лучший ответ

Попробуйте установить расположение новой формы в соответствии с первой, существующей формой. Убедитесь, что для свойства второй формы StartPosition установлено значение "Manual". Это предполагает, что ваши формы являются одинаковыми размерами.

Пример конструктора "плавающей" формы:

// reference to the form underneath, as it might
// change location between creating the FloatingWindow, and showing
// FloatingWindow!
Form BeneathWindow;

public FloatingWindow(Form BeneathWindow)
{
   InitializeComponent();

   // save this for when we show the form
   this.BeneathWindow = BeneathWindow;
   StartPosition = FormStartPosition.Manual;

}

// OnLoad event handler
private void FloatingWindowLoad(object sender, EventArgs e)
{
   Location = BeneathWindow.Location;
}

Если ваши формы не одинаковые размеры, тогда вы, вероятно, захотите их центрировать. Вы можете использовать CenterParent, как предложили другие, или вы можете вручную центрировать их самостоятельно, как мне иногда нравится:

Location = new Point((BeneathWindow.Width - Width)/2 , (BeneathWindow.Height - Height)/2 );

Либо должны работать!

  • 1
    Правильный код, неправильное место. Это относится (только) к событию Load.
  • 0
    @ Хенк: Ты прав! Возможно, что нижнее окно может изменить местоположение после того, как построено вышеупомянутое окно. Сообщение отредактировано, чтобы отразить это.
1

См. свойства:

  • StartPosition, попробуйте установить его в CenterParent

  • Владелец, попробуйте установить его в ParentForm. Или Откройте свое окно с помощью методов:

    //
    // Summary:
    //     Shows the form with the specified owner to the user.
    //
    // Parameters:
    //   owner:
    //     Any object that implements System.Windows.Forms.IWin32Window and represents
    //     the top-level window that will own this form.
    //
    // Exceptions:
    //   System.ArgumentException:
    //     The form specified in the owner parameter is the same as the form being shown.
    public void Show(IWin32Window owner);
    

Или

    //
    // Summary:
    //     Shows the form as a modal dialog box with the specified owner.
    //
    // Parameters:
    //   owner:
    //     Any object that implements System.Windows.Forms.IWin32Window that represents
    //     the top-level window that will own the modal dialog box.
    //
    // Returns:
    //     One of the System.Windows.Forms.DialogResult values.
    //
    // Exceptions:
    //   System.ArgumentException:
    //     The form specified in the owner parameter is the same as the form being shown.
    //
    //   System.InvalidOperationException:
    //     The form being shown is already visible.-or- The form being shown is disabled.-or-
    //     The form being shown is not a top-level window.-or- The form being shown
    //     as a dialog box is already a modal form.-or-The current process is not running
    //     in user interactive mode (for more information, see System.Windows.Forms.SystemInformation.UserInteractive).
    public DialogResult ShowDialog(IWin32Window owner);

Или вы можете сделать это программно:

public partial class ChildForm : Form
{
    public ChildForm(Form owner)
    {
        InitializeComponent();
        this.StartPosition = FormStartPosition.Manual;
        int x = owner.Location.X + owner.Width / 2 - this.Width / 2;
        int y = owner.Location.Y + owner.Height / 2 - this.Height / 2;
        this.DesktopLocation = new Point(x, y);
    }
}

Родительская форма:

public partial class ParentForm : Form
{
    public ParentForm()
    {
        InitializeComponent();
    }

    private void ButtonOpenClick(object sender, EventArgs e)
    {
        ChildForm form = new ChildForm(this);
        form.Show();
    }
}
  • 0
    myDialog.ShowDialog (это); работал для меня (где это родительская форма). Благодарю.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню