///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Displays the MdiForm. /// </summary> /// private void ShowMdiForm() { if (Em.IsTextUI) { MdiForm.Center(MainForm.MdiClient); MdiForm.MdiParent = MainForm; if (!IsModal) { MainForm.LayoutMdi(MdiLayout.Cascade); } } else // GUI { if (MainForm.ActiveMdiChild == null) { MdiForm.Center(MainForm.MdiClient); } if (!IsModal) { MdiForm.MdiParent = MainForm; MdiForm.Visible = true; MdiForm.Focus(); } } }
/// <summary> /// Sets the ReadOnly property of the form. /// </summary> /// protected virtual void SetReadOnly(bool readOnly) { if (IsModal) { readOnly = true; } Debug.TraceLine("{0} *** Setup {1} Mode", TraceID, readOnly ? "View" : "Edit"); MdiForm.InvalidateIf(readOnly != ReadOnly); ReadOnly = readOnly; MdiForm.ReadOnly = readOnly; if (Em.IsGUI && !IsListForm) { MainForm.InfoMessage = this.FormTitle; } if (Em.IsGUI) { MdiForm.ErrorMessage = null; // refresh MDI status message } OnUiStateChanged(); }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Closes the form without asking to save (potentially) dirty data. /// </summary> /// public virtual void QuitForm() { this.ExecuteWithoutFormValidation(() => { MdiForm.IfValidateOk(() => { Debug.TraceLine("{0} Unloading...", TraceID); MdiForm.Unload(); }); }); }
///////////////////////////////////////////////////////////////////////////////// #region [ Constructor ] /// <summary> /// Initializes a new instance of the Form class. /// </summary> /// public Form(int width = 100, int height = 40) : base() { this.Width = width; this.Height = height; this.KeyDown += new KeyEventHandler(ShortcutKeyHandler); ///////////////////////////////////////////////////////////////////////////// // Create tool tip window Application.StatusBarWindow = new ButtonBase() { Name = "toolTip", Parent = this, TabStop = false, Left = 1, Top = this.Height - 1, Width = this.Width - 2, Height = 1, Border = false, ForeColorInact = Application.Theme.ToolTipColor, ToolTipText = Application.DefaultStatusBarText }; ///////////////////////////////////////////////////////////////////////////// // Create MDI client area (which will own and clip all client windows) MdiClient = new MdiForm(Width - 2, Height - 5) { Name = "clientArea", Parent = this, Left = 1, Top = 3, Border = true }; MdiClient.GotFocus += new EventHandler(MdiClient_GotFocus); MdiClient.KeyDown += new KeyEventHandler(ShortcutKeyHandler); MdiClient.ForwadKeysToParent = false; ///////////////////////////////////////////////////////////////////////////// // Create client area (which will own and clip all client windows) Menu = new MainMenu() { Name = "mainMenu", Parent = this, Left = 1, Top = 1, Width = this.Width - 2, Height = 1, }; Menu.KeyDown += new KeyEventHandler(ShortcutKeyHandler); Menu.ExitMenu += (sender, e) => { if (this.ActiveChild == Menu && MdiClient.Children.Count != 0) { MdiClient.Focus(); } }; Menu.Show(); }
public void OnMdiOut() { if (MdiForm == null) { return; } MdiForm.RemoveTab(this); this.MdiParent = null; this.WindowState = FormWindowState.Normal; userToolStrip.IsVisibleMdiButton = false; }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Selects the first control with the tab stop. /// </summary> /// private void FocusOnFirstTabStop() { if (FirstField.TabStop) { FirstField.Focus(); } else { MdiForm.SelectNextControl(FirstField, /*forward*/ true, /*tabStopOnly*/ true, /*nested*/ true, /*wrap*/ true); } }
private void BaseForm_FormClosing(object sender, FormClosingEventArgs e) { try { if (MdiForm != null) { MdiForm.RemoveTab(this); } timer1.Stop(); timer1.Dispose(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
/// <summary> /// Validates text value to be a valid date in specified format and, if validation /// succedes, returns the parsed value. /// </summary> /// public DateTime ValidateDate(string fieldName, string value, string format, string infoFormat, CancelEventArgs e) { if (e.Cancel) { return(DateTime.MinValue); // Already cancelled } // MdiForm.ErrorMessage = null; if (ReadOnly) { return(DateTime.MinValue); // Assume always data valid while browsing } value = value == null ? null : value.Trim(); // Accept NULL values always as valid. Not null must be validated separatelly. // if (string.IsNullOrEmpty(value)) { return(DateTime.MinValue); } // Parse integer // try { if (format != null) { return(DateTime.ParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture)); } else { return(DateTime.Parse(value, System.Globalization.CultureInfo.InvariantCulture)); } } catch (Exception) { MdiForm.ErrorMessage = fieldName + " must be a valid date" + infoFormat; MdiForm.Beep(); e.Cancel = true; } return(DateTime.MinValue); }
/// <summary> /// Creates a new static text at specified location. /// </summary> /// <remarks> /// In TextUI mode a static text is drawed on MdiForm canvas. /// In GUI mode a new MyLabel control is created instead. /// </remarks> /// protected void NewStaticText(float left, float top, string text) { #if TEXTUI MdiForm.At((int)left, (int)top).Write(text); #else new MyLabel() { Left = (int)(left * Em.Width), Top = (int)(top * Em.Height), TabStop = false, TabIndex = NextTabIndex, TextAlign = ContentAlignment.MiddleLeft, AutoSize = true, Text = text, Parent = MdiForm, }; #endif }
///////////////////////////////////////////////////////////////////////////////////// #region [ Private Methods ] /// <summary> /// Initializes event handlers of the MdiForm and its visual components. /// </summary> /// private void InitializeMdiForm() { // Hook our event handlers this.UiStateChanged += (sender, e) => { MdiForm.UpdateVisualStatus(); }; MdiForm.Validating += (sender, e) => { e.Cancel = !IsSafeToLeaveTheForm(); }; MdiForm.FormClosed += (sender, e) => { DisconnectFromCollection(); }; MdiForm.KeyDown += (sender, e) => { if (e.KeyCode == Keys.F2 && e.Modifiers == 0) { ToggleReadOnlyMode(); e.Handled = true; } }; // In GUI mode we need also to initialize MdiForm's font and icon // and, in case of list form, adjust MdiForm's width/height ratio. #if !TEXTUI MdiForm.Font = MainForm.Font; MdiForm.SetupIcon(this.Caption); if (IsListForm) { MdiForm.Width = (int)(MdiForm.Width * 1.25f); MdiForm.Height = (int)(MdiForm.Height * 0.75f); MdiForm.MinimumSize = MdiForm.Size; } #endif }
private void UserToolStrip_MdiChangedEvent(object sender, EventArgs e) { //if (sender.ToString() == "IN") //{ // this.MdiParent = MdiForm; // MdiForm.AddTab(this); //} if (sender.ToString() == "OUT") { if (MdiForm == null) { return; } //MdiForm.RemoveForm(this); MdiForm.RemoveTab(this); this.MdiParent = null; this.WindowState = FormWindowState.Normal; } }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Opens the form in specified mode (browsing, searching, editing or add new). /// </summary> /// public override void OpenForm(OpenMode mode) { if (mode == OpenMode.AddNew) { Record = null; } MdiForm.SuspendLayout(); if (IsAddNew) { mode = OpenMode.Edit; // Force edit mode if adding new records } base.OpenForm(mode); FocusOnFirstTabStop(); MdiForm.ResumeLayout(); }
/// <summary> /// Validates text value to be a valid HTTP or HTTPS Universal Resource Identifier /// (URI). /// </summary> /// public void ValidateHttpURI(string fieldName, string value, CancelEventArgs e) { if (e.Cancel) { return; // Already cancelled } // MdiForm.ErrorMessage = null; if (ReadOnly) { return; // Assume always data valid while browsing } value = value == null ? null : value.Trim(); // Accept NULL values always as valid. Not null must be validated separatelly. // if (string.IsNullOrEmpty(value)) { return; } // Parse URI and accept only URIs having scheme either http or https // try { string scheme = new Uri(value.Trim()).Scheme.ToLower(); if (scheme != "http" && scheme != "https") { throw new Exception(fieldName + " must be either http or https URI."); } } catch (Exception ex) { MdiForm.ErrorMessage = ex.Message; MdiForm.Beep(); e.Cancel = true; } }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Saves data and sets the form read-only (locks the form for changes). /// </summary> /// protected virtual void SaveAndLock() { ExecuteWithoutFormValidation(() => { MdiForm.IfValidateOk(() => { try { Debug.TraceLine("{0} Saving data...", TraceID); OnSaveData(); SetReadOnly(true); } catch (Exception ex) // Catch any property violations { MessageBox.Show(ex.Message, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } }); }); }
public FormularioListView(Type tipo) { crudForm = new MdiForm(); this.Tipo = tipo; ListView = new ListBox(); ListView.Size = new Size(600, 300); ListView.Location = new Point(50, 50); ListView.Font = new Font("Arial", 14); ListView.SelectedValueChanged += ListView_SelectedValueChanged; var props = this.GetType().GetProperties().Where(p => p.PropertyType == typeof(Button)).ToList(); var posicaoY = 40; foreach (var item in props) { item.SetValue(this, new Button()); var botao = (Button)item.GetValue(this); botao.Size = new Size(135, 50); botao.Dock = DockStyle.Right; botao.Text = modelocrud.formatarTexto(item.Name); botao.Location = new Point(570, posicaoY); botao.Font = new Font("Arial", 14); Controls.Add(botao); posicaoY += 80; } MudancaEstado.Click += MudancaEstado_Click; Deletar.Click += botaoExcluir_Click; Atualizar.Click += botaoAtualizar_Click; Detalhes.Click += BotaoDetalhes_Click; AtualizarLista.Click += BotaoAtualizarLista_Click; Controls.Add(ListView); this.ListView = ListView; InitializeComponent(); }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Toggles read-only mode on/off. /// </summary> /// public void ToggleReadOnlyMode() { if (IsModal) { return; } // Note that IfValidateOk () can trigger validation // which may change Browsing mode, so it is good to remember current browsing // mode so we could detect if it was changed. // bool wasReadOnly = ReadOnly; if (MdiForm.IfValidateOk()) // here we lose focus temporarily if we can { // Focus could be lost, so we may change editing mode... // if (ReadOnly == wasReadOnly) // i.e. not changed while validating { SetReadOnly(!wasReadOnly); // toggle mode } } }
///////////////////////////////////////////////////////////////////////////////////// #region [ Validation Helper Methods ] /// <summary> /// Validates text value not to be null or empty. /// </summary> /// public void ValidateNotNull(string fieldName, string value, CancelEventArgs e) { if (e.Cancel) { return; // Already cancelled } // MdiForm.ErrorMessage = null; if (ReadOnly) { return; // Assume always data valid while browsing } value = value == null ? null : value.Trim(); if (string.IsNullOrEmpty(value)) { MdiForm.ErrorMessage = fieldName + " must not be empty or null."; MdiForm.Beep(); e.Cancel = true; } }
/// <summary> /// Validates text value to be a valid decimal number and, if validation succedes, /// returns the parsed value. /// </summary> /// public void ValidateDecimal(string fieldName, string value, CancelEventArgs e, ref decimal parsedValue) { if (e.Cancel) { return; // Already cancelled } // MdiForm.ErrorMessage = null; if (ReadOnly) { return; // Assume always data valid while browsing } value = value == null ? null : value.Trim(); // Accept NULL values always as valid. Not null must be validated separatelly. // if (string.IsNullOrEmpty(value)) { return; } // Parse integer // try { parsedValue = decimal.Parse(value); } catch (Exception) { MdiForm.ErrorMessage = fieldName + " must be a valid decimal number."; MdiForm.Beep(); e.Cancel = true; } }
/// <summary> /// Validates text value to be a valid E-Mail address (consisting of at least /// one '@' and '.' charaters where '@' preceedes '.'). /// </summary> /// public void ValidateEMailAddress(string fieldName, string value, CancelEventArgs e) { if (e.Cancel) { return; // Already cancelled } // MdiForm.ErrorMessage = null; if (ReadOnly) { return; // Assume always data valid while browsing } value = value == null ? null : value.Trim(); // Accept NULL values always as valid. Not null must be validated separatelly. // if (string.IsNullOrEmpty(value)) { return; } // Confirm that there is an "@" and a "." in the e-mail address, and in // the correct order. // int monkey = value.IndexOf("@"); if (monkey < 0 || value.IndexOf(".", monkey) < monkey) { MdiForm.ErrorMessage = fieldName + " must be valid e-mail address format."; MdiForm.Beep(); e.Cancel = true; } }
/// <summary> /// Initializes UI components of the MdiForm. /// </summary> /// protected override void InitializeComponents() { ///////////////////////////////////////////////////////////////////////////////// // Table layout grid definition, with rows and columns in Em units. float[] col = { 4, 23 }; float[] row = { 2, 5, 8, 11 }; float maxLen = 24; // Maximum text length ///////////////////////////////////////////////////////////////////////////////// // Static text int r = 0, c = 0; NewStaticText(col[c], row[r++], "Membership: "); NewStaticText(col[c], row[r++], "Price Class: "); NewStaticText(col[c], row[r++], "Minimum Quantity:"); NewStaticText(col[c], row[r++], "Rental Fee: "); ///////////////////////////////////////////////////////////////////////////////// // TextBox and ComboBox Fields r = 0; c = 1; this.membership = NewEnumField(col[c], row[r++], maxLen, typeof(Membership)); this.priceClass = NewEnumField(col[c], row[r++], maxLen, typeof(PriceClass)); this.textMinQuantity = NewTextField(col[c], row[r++], maxLen); this.textRentalFee = NewTextField(col[c], row[r++], maxLen); ///////////////////////////////////////////////////////////////////////////////// // Field validation event handlers this.textMinQuantity.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.textMinQuantity.ContentsChanged) { return; } string fieldName = "Minimum Quantity"; // Verify (and parse) field as not null integer number // ValidateNotNull(fieldName, this.textMinQuantity.Text, e); int fieldValue = 0; ValidateInteger(fieldName, this.textMinQuantity.Text, e, ref fieldValue); // Minimum Quantity must be an integer >= 1 // if (!e.Cancel && fieldValue > 0) { minimumQuantity = fieldValue; } else if (!e.Cancel) { MdiForm.ErrorMessage = fieldName + " must be greater or equal one."; MdiForm.Beep(); e.Cancel = true; } }; this.textRentalFee.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.textRentalFee.ContentsChanged) { return; } // Verify (and parse) field as not null decimal number // string fieldName = "Rental Fee"; ValidateNotNull(fieldName, this.textRentalFee.Text, e); decimal fieldValue = 0; ValidateDecimal(fieldName, this.textRentalFee.Text, e, ref fieldValue); // Rental fee must be a positive decimal. // if (!e.Cancel && fieldValue > 0) { rentalFee = fieldValue; } else if (!e.Cancel) { MdiForm.ErrorMessage = fieldName + " must be greater than zero."; MdiForm.Beep(); e.Cancel = true; } }; ///////////////////////////////////////////////////////////////////////////////// this.membership.TabStop = false; this.membership.ReadOnly = true; this.priceClass.TabStop = false; this.priceClass.ReadOnly = true; this.textMinQuantity.TabStop = false; this.textMinQuantity.ReadOnly = true; base.InitializeComponents(); }
/// <summary> /// Initializes UI components of the MdiForm. /// </summary> /// protected override void InitializeComponents() { ///////////////////////////////////////////////////////////////////////////////// // Table layout grid definition, with rows and columns in Em units. float[] col = { 3, 18, 40, 50, 79 }; float[] row = { 2, 4, 7, 9, 11, 12, 14, 16, 18, 21, 22 }; float maxLen = 15; // Maximum text length ///////////////////////////////////////////////////////////////////////////////// // Static text int r = 2, c = 0; NewStaticText(col[c], row[r++], "Due Date:"); NewStaticText(col[c], row[r++], "Rental Fee:"); ///////////////////////////////////////////////////////////////////////////////// // Customer info label this.customerInfo = NewLabel(col[0], row[0] - (Em.IsGUI ? 0.2f : 0f), (float)MdiForm.Width / Em.Width - col[0] * 2 ); this.exemplarInfo = NewLabel(col[0], row[1] + (Em.IsGUI ? 0.2f : 0f), (float)MdiForm.Width / Em.Width - col[0] * 2 ); this.exemplarSelect = new MyButton() { Left = (int)(col[2] * Em.Width), Top = (int)((row[2] - (Em.IsGUI ? 0.2f : 0f)) * Em.Height), Text = "&Select Movie Exemplar", AutoSize = true, TabStop = true, TabIndex = NextTabIndex, Parent = MdiForm, }; ///////////////////////////////////////////////////////////////////////////////// // TextBox fields r = 2; c = 1; this.dueDate = NewTextField(col[c], row[r++], maxLen); this.rentalFee = NewTextField(col[c], row[r++], maxLen); ///////////////////////////////////////////////////////////////////////////////// // Field validation event handlers this.dueDate.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.dueDate.ContentsChanged) { return; } ValidateNotNull("Due date", this.dueDate.Text, e); ValidateDate("Due date", this.dueDate.Text, "yyyy-M-d", " in ISO format (yyyy-mm-dd).", e); }; this.rentalFee.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.rentalFee.ContentsChanged) { return; } string fieldName = "Rental Fee"; ValidateNotNull(fieldName, this.dueDate.Text, e); decimal fieldValue = 0; // default value to satisfy validation if null ValidateDecimal(fieldName, this.rentalFee.Text, e, ref fieldValue); // Rental fee must be either null or an decimal >= 0 // if (!e.Cancel && fieldValue <= 0) { MdiForm.ErrorMessage = fieldName + " must not be a positive number."; MdiForm.Beep(); e.Cancel = true; } }; ///////////////////////////////////////////////////////////////////////////////// // Movie Exemplar Selection as modal MovieExemplarListForm (i.e. dialog) this.exemplarSelect.Click += (sender, e) => { this.ExecuteWithoutFormValidation(() => { MovieExemplarListForm form = new MovieExemplarListForm(); form.CommonFilter = ex => !ex.IsRented; form.OpenModal(this.Exemplar, selectedExemplar => { this.Exemplar = selectedExemplar; this.exemplarInfo.Text = selectedExemplar.ToString(); this.exemplarChanged = true; if (this.Customer != null) { decimal fee = MainForm.VideoStore.GetPrice( this.Customer.Membership, this.Exemplar.PriceClass, this.Customer.RentedItemsCount + 1); this.rentalFee.Text = fee.ToString("0.00"); } form.QuitForm(); this.dueDate.Select(); }); }); }; ///////////////////////////////////////////////////////////////////////////////// // Customer info GUI/TUI specific setup // #if TEXTUI MdiForm.GotFocus += (sender, e) => { this.customerInfo.ForeColorInact = Color.White; this.customerInfo.ForeColor = Color.White; this.exemplarInfo.ForeColorInact = Color.Cyan; this.exemplarInfo.ForeColor = Color.Cyan; }; #else this.customerInfo.Font = MainForm.HeadingFont; this.customerInfo.Height = Em.Height * 15 / 10; this.customerInfo.ForeColor = Color.DarkBlue; this.customerInfo.AutoSize = false; this.customerInfo.AutoEllipsis = true; this.exemplarInfo.Height = Em.Height + (Em.IsGUI ? 2 : 0); this.exemplarInfo.ForeColor = Color.DarkRed; this.exemplarInfo.AutoSize = false; this.exemplarInfo.AutoEllipsis = true; this.MdiForm.FontChanged += (sender, e) => { this.customerInfo.Font = MainForm.HeadingFont; this.customerInfo.Height = Em.Height * 15 / 10; this.exemplarInfo.Height = Em.Height + (Em.IsGUI ? 2 : 0); }; #endif ///////////////////////////////////////////////////////////////////////////////// base.InitializeComponents(); }
///////////////////////////////////////////////////////////////////////////////////// #region [ Overriden Base Methods ] protected override void InitializeComponents() { ///////////////////////////////////////////////////////////////////////////////// // Table layout grid definition, with rows and columns in Em units. float[] col = { 3, 17, 44, 57 }; float[] row = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22 }; float colWidth = 24; // default column width ///////////////////////////////////////////////////////////////////////////////// // Static text int r = 0, c = 0; NewStaticText(col[c], row[r++], "First Name:"); NewStaticText(col[c], row[r++], "Last Name:"); NewStaticText(col[c], row[r++], "Person ID:"); NewStaticText(col[c], row[r++], "Membership:"); NewStaticText(col[c], row[r++], "Address:"); NewStaticText(col[c], row[r++], "Post Code:"); NewStaticText(col[c], row[r++], "City:"); NewStaticText(col[c], row[r++], "Country:"); // Mandatory fields marker: NewStaticText(col[c] - 2, row[0], "*"); NewStaticText(col[c] - 2, row[1], "*"); NewStaticText(col[c] - 2, row[2], "*"); r = 0; c = 2; NewStaticText(col[c], row[r++], "Phone:"); NewStaticText(col[c], row[r++], "Cell Phone:"); NewStaticText(col[c], row[r++], "E-Mail:"); ///////////////////////////////////////////////////////////////////////////////// // TextBox fields r = 0; c = 1; this.firstName = NewTextField(col[c], row[r++], colWidth); this.lastName = NewTextField(col[c], row[r++], colWidth); this.personID = NewTextField(col[c], row[r++], colWidth); this.membership = NewEnumField(col[c], row[r++], Em.IsGUI ? colWidth : 0, typeof(Membership)); this.address = NewTextField(col[c], row[r++], colWidth); this.postCode = NewTextField(col[c], row[r++], colWidth); this.city = NewTextField(col[c], row[r++], colWidth); this.country = NewTextField(col[c], row[r++], colWidth); r = 0; c = 3; this.phone = NewTextField(col[c], row[r++], colWidth); this.cellPhone = NewTextField(col[c], row[r++], colWidth); this.email = NewTextField(col[c], row[r++], colWidth); ///////////////////////////////////////////////////////////////////////////////// // Credit Card Group Box MyGroupBox ccBox = NewGroupBox("Credit Card", col[2] - (Em.IsGUI ? 1f : 2f), row[r] + (Em.IsGUI ? 0.6f : 1f), 38, (Em.IsGUI ? 8.6f : 9f) ); NewLabel(ccBox, 2, 2, "Type:"); NewLabel(ccBox, 2, 4, "Number:"); NewLabel(ccBox, 2, 6, "Valid Thru:"); int offset = Em.IsGUI ? 14 : 15; this.creditCard = NewEnumField(ccBox, offset, 2, Em.IsGUI ? 22 : 0, typeof(CreditCardType)); this.creditCardNumber = NewTextField(ccBox, offset, 4, Em.IsGUI ? 22 : 19); this.creditCardValid = NewTextField(ccBox, offset, 6, Em.IsGUI ? 10 : 8); ///////////////////////////////////////////////////////////////////////////////// // Field validation event handlers this.firstName.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.firstName.ContentsChanged) { return; } ValidateNotNull("Customer's first name", this.firstName.Text, e); }; this.lastName.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.lastName.ContentsChanged) { return; } ValidateNotNull("Customer's last name", this.lastName.Text, e); }; this.personID.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.personID.ContentsChanged) { return; } ValidateNotNull("Customer's Person-ID", this.personID.Text, e); if (!ReadOnly && !e.Cancel) { string notValidInfo = Customer.ValidatePNR(this.personID.TrimmedText); if (notValidInfo != null) { MdiForm.ErrorMessage = notValidInfo; MdiForm.Beep(); e.Cancel = true; } } }; this.email.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.email.ContentsChanged) { return; } ValidateEMailAddress("E-Mail", this.email.Text, e); }; this.creditCard.SelectedIndexChanged += (sender, e) => { CreditCardType?ccType = this.creditCard.Current.Tag as CreditCardType?; if (ccType.HasValue && ccType.Value != CreditCardType.None) { this.creditCardNumber.TabStop = true; this.creditCardNumber.Enabled = true; this.creditCardValid.TabStop = true; this.creditCardValid.Enabled = true; } else { // this.creditCardNumber.Text = null; this.creditCardNumber.TabStop = false; this.creditCardNumber.Enabled = false; // this.creditCardValid.Text = null; this.creditCardValid.TabStop = false; this.creditCardValid.Enabled = false; } }; this.creditCardNumber.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.creditCardNumber.ContentsChanged) { return; } CreditCardType?ccType = this.creditCard.Current.Tag as CreditCardType?; if (ccType.HasValue && ccType.Value != CreditCardType.None) { string ccNumber = this.creditCardNumber.TrimmedText; // ValidateNotNull( "Credit Card Number", ccNumber, e ); // Credit card number valiation will be performed when record // is updated. } }; this.creditCardValid.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.creditCardValid.ContentsChanged) { return; } CreditCardType?ccType = this.creditCard.Current.Tag as CreditCardType?; if (ccType.HasValue && ccType.Value != CreditCardType.None) { // ValidateNotNull( "Valid Thru", this.creditCardValid.Text, e ); ValidateDate("Valid Thru", this.creditCardValid.Text, "yyyy-M", " in 'yyyy-mm' format.", e); } }; ///////////////////////////////////////////////////////////////////////////////// base.InitializeComponents(); }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes UI components of the DetailsForm. /// </summary> /// <remarks> /// Sets the FirstField control and creates ButtonPanel. /// </remarks> /// protected override void InitializeComponents() { FirstField = MdiForm.Children[0] as Control; foreach (var child in MdiForm.Children) { Control ctrl = child as Control; if (ctrl != null && ctrl.TabStop) { FirstField = ctrl; break; } } FirstField.Focus(); ///////////////////////////////////////////////////////////////////////////////// if (Em.IsTextUI) { MdiForm.ForeColor = Color.DarkCyan; } ///////////////////////////////////////////////////////////////////////////////// // Buttons Button_OK = new MyButton() { AutoSize = true, TabStop = false }; Button_Locker = new MyButton() { AutoSize = true, TabStop = false }; Button_Delete = new MyButton() { AutoSize = true, TabStop = false }; Button_Link = new MyButton() { AutoSize = true, TabStop = false }; Button_Info = new MyButton() { AutoSize = true, TabStop = false }; Button_Cancel = new MyButton() { AutoSize = true, TabStop = false }; ///////////////////////////////////////////////////////////////////////////////// Button_OK.Click += delegate { if (ReadOnly) { QuitForm(); } else { SaveAndLock(); } }; Button_Locker.Click += (sender, e) => ToggleReadOnlyMode(); Button_Delete.Click += (sender, e) => RaiseDeleteClick(); Button_Link.Click += (sender, e) => RaiseLinkClick(); Button_Info.Click += (sender, e) => RaiseInfoClick(); Button_Cancel.Click += (sender, e) => QuitForm(); ///////////////////////////////////////////////////////////////////////////////// buttonCollection = new MyButton[] { Button_OK, Button_Locker, Button_Delete, Button_Link, Button_Info, Button_Cancel, }; ///////////////////////////////////////////////////////////////////////////////// #if TEXTUI MdiForm.DrawFrame(1, MdiForm.Height - 4, MdiForm.Width - 2, 1); #else MdiForm.Controls.Add(new MyLineSeparator() { Dock = DockStyle.Bottom }); ButtonPanel = new FlowLayoutPanel() { Dock = DockStyle.Bottom, AutoSize = true, Padding = new Padding(2 * Em.Width, Em.Height / 2, 0, Em.Height / 2), TabStop = false, TabIndex = 10000, }; MdiForm.Controls.Add(ButtonPanel); #endif ///////////////////////////////////////////////////////////////////////////////// base.InitializeComponents(); }
///////////////////////////////////////////////////////////////////////////////// // Constructs sample application form. // public TestClient_TUI() : base(100, 40) { this.Text = applicationTitle; this.WindowUnloaded += new EventHandler(EH_WindowUnloaded); ///////////////////////////////////////////////////////////////////////////// // Client Area default text MdiClient.Border = false; MdiClient.SetSize(Width, Height - 3); --MdiClient.Left; --MdiClient.Top; MdiClient.ForeColor = Color.DarkCyan; MdiClient.FillRectangle(0, 0, MdiClient.Width, MdiClient.Height, '▒'); MdiClient.DrawFrame(0, 0, MdiClient.Width, MdiClient.Height); MdiClient.BackColor = BackColor; MdiClient.ForeColor = ForeColor; MdiClient.SetCursorPosition(60, 3); MdiClient.WriteLine("Text User Interface Test Suite\r\n"); MdiClient.WriteLine("▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒"); MdiClient.WriteLine("ABCDEFGHIJKLMNOPQRSTUVWXYZÖÅÄÉ\r\n" + "abcdefghijklmnopqrstuvwxyzåäöé\n" + "\b\b\b«☺»" + "\r0123456789"); MdiClient.WriteLine("▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒"); MdiClient.SetColors(60, 5, 30, 5, Color.Black, Color.DarkGray); ///////////////////////////////////////////////////////////////////////////// // Application main menu Menu.MenuItems.Add(new MenuItem("-")); // test invalid separator MenuItem miEditor = new MenuItem("&Editor"); miEditor.ToolTipText = "Sets editor window in focus"; Menu.MenuItems.Add(miEditor); miEditor.Click += new EventHandler(EH_SetEditorInFocus); Menu.MenuItems.Add(new MenuItem("-")); // test invalid separator Menu.MenuItems.Add(new MenuItem("-")); // test invalid separator MenuItem miRed = new MenuItem("&Red"); miRed.ToolTipText = "Sets red window in focus."; Menu.MenuItems.Add(miRed); miRed.Click += new EventHandler(EH_SetRedInFocus); MenuItem miCyan = new MenuItem("&Cyan"); miCyan.ToolTipText = "Sets cyan window in focus."; Menu.MenuItems.Add(miCyan); miCyan.Click += new EventHandler(EH_SetCyanInFocus); MenuItem miSubmenu = new MenuItem("&Misc..."); miSubmenu.ToolTipText = "Grid test, button test and message box tests are here..."; Menu.MenuItems.Add(miSubmenu); Menu.MenuItems.Add(new MenuItem("-")); // test invalid separator ///////////////////////////////////////////////////////////////////////////// // Client window: Moveable winMoveable = new ButtonBase() { Name = "winMoveable", Left = 50, Top = 15, Width = 25, Height = 11, Border = true, BorderForeColor = Color.Yellow, BackColor = Color.DarkBlue, ForeColor = Color.Gray, }; winMoveable.DrawContents += new DrawEventHandler(EH_winMoveable_DrawContents); ///////////////////////////////////////////////////////////////////////////// // Client window: Cyan and SubCyan winCyan = new ButtonBase() { Name = "winCyan", TabStop = true, Left = 54, Top = 20, Width = 22, Height = 7, Border = true, BorderForeColor = Color.Green, BackColor = Color.DarkBlue, ForeColor = Color.Gray, Text = "Cyan Window:" }; textBoxSubCyan = new TextBox() { Name = "winSubCyan", Parent = winCyan, Multiline = false, Left = 1, Top = 2, Width = 20, Height = 1, BackColor = Color.DarkMagenta, ForeColor = Color.Cyan, ForeColorInact = Color.Gray, ToolTipText = "Cyan Window; Tests single-line text box with validation..." }; textBoxSubCyan.KeyDown += new KeyEventHandler(EH_winSubCyan_KeyDown); textBoxSubCyan.GotFocus += new EventHandler(EH_winSubCyan_GotFocus); checkBoxSubCyan = new CheckBox() { Name = "checkBoxSubCyan", Parent = winCyan, Left = 1, Top = 4, Width = 20, Height = 1, BackColor = Color.DarkMagenta, ForeColor = Color.Cyan, ForeColorInact = Color.Gray, Text = "Check box", ToolTipText = "Cyan Window; Checkbox to test..." }; checkBoxSubCyan.KeyDown += new KeyEventHandler(EH_winSubCyan_KeyDown); textBoxSubCyan.Validating += new CancelEventHandler(EH_textBoxSubCyan_Validating); ///////////////////////////////////////////////////////////////////////////// // Client window: Buffered drawBox = new MdiForm(21, 15) { Name = "winBuf", TabStop = false, Left = MdiClient.Width - 23, Top = MdiClient.Height - 17, Border = true }; drawBox.Write("Draw Box"); drawBox.ForeColor = Color.DarkMagenta; drawBox.DrawFrame(3, 3, 15, 10, BoxLines.NotJoined); drawBox.DrawFrame(3, 5, 15, 1, BoxLines.Joined); drawBox.DrawFrame(5, 3, 1, 10, BoxLines.Joined); drawBox.ForeColor = Color.Green; drawBox.CursorTop = 4; drawBox.CursorLeft = 8; drawBox.Write(" Test "); ///////////////////////////////////////////////////////////////////////////// // Client window: Red winRead = new ButtonBase() { Name = "winRed", TabStop = true, ToolTipText = "Red Window; Shift+Arrows moves only draw box, " + "Control+Arrows resizes draw box", Left = 75, Top = 18, Width = 20, Height = 10, Border = true, BackColor = Color.DarkRed, ForeColor = Color.Yellow, BackColorInact = Color.DarkRed, ForeColorInact = Color.DarkYellow, Text = "Red Window:", ForwadKeysToParent = true }; winRead.KeyDown += new KeyEventHandler(EH_winRed_KeyDown); winRead.GotFocus += new EventHandler(EH_winRed_GotFocus); winRead.LostFocus += new EventHandler(EH_winRed_LostFocus); ///////////////////////////////////////////////////////////////////////////// // Client window: Editor textBoxEditor = new TextBox() { Name = "winEditor", Multiline = true, ToolTipText = "Press F2 to load file 'VRO-test.txt' or AppKey for ListBox ...", Left = 5, Top = 5, Width = 40, Height = 15, VerticalScrollBar = true, Border = true, Caption = "TextBox as Editor", Text = "0 Editor\r\n" + "1\r\n" + "2\r\n" + "3\r\n" + "4\r\n" + "5\r\n" + "6 234567890123456789012345678901234567890123456789\r\n" + "7\r\n" + "8\r\n" + "9\r\n" + "10 sdfasdfasdfasfasfasdf1\r\n" + "11\r\n" + "12\r\n" + "1\b3 backspace\r\n" + "tabs\ta\tab\tabc\tabcd\tabcde\tabcdef\r\n" + "15\r\n" + "16\r\n" + "17\r\n" + "18\r\n" + "19\r\n" }; textBoxEditor.KeyDown += new KeyEventHandler(EH_winEditor_KeyDown); ///////////////////////////////////////////////////////////////////////////// // List box listBox = new ListBox() { Name = "listBox", Left = 5, Top = 5, Width = 40, Height = 15, VerticalScrollBar = true, Border = true, CaptionForeColor = Color.Red, Caption = "List Box (copied from TextBox)", Header = new string[] { string.Empty, " Header", string.Empty, ListBoxBase.WideDivider, }, Footer = new string [] { ListBoxBase.WideDivider, " Footer", } }; listBox.KeyDown += new KeyEventHandler(EH_listBox_KeyDown); ///////////////////////////////////////////////////////////////////////////// // Vertical submenu miSubmenu.MenuItems.Add(new MenuItem("-")); // test invalid sep. MenuItem miShowGrid = new MenuItem("Show &grid window"); miShowGrid.ToolTipText = "Shows a lots of windows in a grid..."; miSubmenu.MenuItems.Add(miShowGrid); miShowGrid.Click += new EventHandler(EH_ShowGridWindow); miSubmenu.MenuItems.Add(new MenuItem("-")); MenuItem m13 = new MenuItem("Test &Error Recovery"); m13.ToolTipText = "Throws exception"; miSubmenu.MenuItems.Add(m13); m13.Click += delegate { throw new Exception("Error Recovery Test"); }; miSubmenu.MenuItems.Add(new MenuItem("-")); MenuItem miTestButton = new MenuItem( "&&Long submenu item that && opens test &button (& multiple &&s) "); miTestButton.ToolTipText = "&&Long submenu item that && opens test &button (& multiple &&s) "; miSubmenu.MenuItems.Add(miTestButton); miTestButton.Click += new EventHandler(EH_SetTestButtonInFocus); miSubmenu.MenuItems.Add(new MenuItem("-")); // test invalid sep. ///////////////////////////////////////////////////////////////////////////// // Button buttonTest = new Button() { Name = "buttonTest", Border = true, Left = 5, Top = 10, AutoSize = true, HorizontalPadding = 2, // VerticalPadding = 1, Text = "Test Button\nwith very long line\nand the third line", ToolTipText = "Press ENTER to hide the button..." }; buttonTest.Click += new EventHandler(EH_buttonTest_Click); buttonTest2 = new Button() { Name = "buttonTest2", Border = true, Left = 5 + buttonTest.Width + 2, Top = 10, AutoSize = true, HorizontalPadding = 2, // VerticalPadding = 1, Text = "Test Button 2\nwith very long line\nand the third line", ToolTipText = "Press ENTER to hide the button...", TextAlign = TextAlign.Right }; buttonTest2.Click += new EventHandler(EH_buttonTest_Click); }
public MDIEsboco() { crudForm = new MdiForm(); InitializeComponent(); }
///////////////////////////////////////////////////////////////////////////////////// #region [ Overriden Base Methods ] /// <summary> /// Initializes UI components of the MdiForm. /// </summary> /// protected override void InitializeComponents() { ///////////////////////////////////////////////////////////////////////////////// // Table layout grid definition, with rows and columns in Em units. float[] col = { 3, 18, 47, 63, 79 }; float[] row = { 2, 4, 6, 8, 10, 12, 14, 17, 19, 21, 22 }; float maxLen = 24; // Maximum text length ///////////////////////////////////////////////////////////////////////////////// // Static text int r = 0, c = 0; NewStaticText(col[c] - 2, row[r++], "*"); NewStaticText(col[c], row[r++], "First Release:"); NewStaticText(col[c], row[r++], "Duration:"); NewStaticText(col[c], row[r++], "Country:"); NewStaticText(col[c], row[r++], "Language:"); NewStaticText(col[c], row[r++], "PG-Rate:"); NewStaticText(col[c], row[r++], "IMDB:"); NewStaticText(col[c] + 21, row[2], "(min)"); ///////////////////////////////////////////////////////////////////////////////// // TextBox fields r = 0; c = 1; this.labelTitle = NewLabel(col[0], row[0], 10); this.labelTitle.UseMnemonic = true; this.labelTitle.Text = "&Title:"; // Always move focus from title label to movie title // this.labelTitle.GotFocus += (sender, e) => this.movieTitle.Focus(); this.movieTitle = NewTextField(col[c], row[r++], maxLen); this.release = NewTextField(col[c], row[r++], maxLen); this.duration = NewTextField(col[c], row[r++], 5); this.country = NewTextField(col[c], row[r++], maxLen); this.language = NewTextField(col[c], row[r++], maxLen); this.pgRate = NewTextField(col[c], row[r++], maxLen); this.imdb = NewTextField(col[c], row[r++], maxLen); ///////////////////////////////////////////////////////////////////////////////// // ChecBoxes for Genre MyGroupBox genreBox = NewGroupBox("&Genre", col[2] - 3, row[0] - (Em.IsGUI ? 0.5f : 0f), 34, 14); this.genre = new MyCheckBoxCollection(typeof(Genre)); r = 0; c = 0; foreach (CheckBox cb in this.genre) { cb.Parent = genreBox; cb.TabIndex = NextTabIndex; cb.Left = (int)((2f + c * 16f) * Em.Width); cb.Top = (int)(Em.IsGUI ? 1.4f * Em.Height : 2f * Em.Height); #if TEXTUI cb.Height = Em.Height; cb.Width = 15 * Em.Width; #else cb.AutoSize = true; #endif cb.Top += (r++) * (Em.IsGUI ? Em.Height + 3 : Em.Height); if (r >= 10) { r = 0; if (++c > 3) { break; } } } ///////////////////////////////////////////////////////////////////////////////// // Multiline TextBox: Directors r = 7; c = 1; if (Em.IsGUI) { row[8] -= 0.4f; } this.labelDirectors = NewLabel(col[0], row[r], 18); this.labelDirectors.UseMnemonic = true; this.labelDirectors.Text = "Di&rectors"; this.labelDirectors.Height = Em.Height; this.directors = NewTextField(col[0], row[r + 1], 18); this.directors.Multiline = true; this.directors.Height = 5 * Em.Height + (Em.IsGUI ? 4 : 0); this.directors.AutoScrollBar = true; // Always move focus from directors label to directors field // this.labelDirectors.GotFocus += (source, e) => this.directors.Focus(); ///////////////////////////////////////////////////////////////////////////////// // Multiline TextBox: Writers this.labelWriters = NewLabel(col[0] + 20, row[r], 18); this.labelWriters.UseMnemonic = true; this.labelWriters.Text = "&Writers"; this.labelWriters.Height = Em.Height; this.writers = NewTextField(col[0] + 20, row[r + 1], 18); this.writers.Multiline = true; this.writers.Height = 5 * Em.Height + (Em.IsGUI ? 4 : 0); this.writers.AutoScrollBar = true; // Always move focus from writers label to writers field // this.labelWriters.GotFocus += (source, e) => this.writers.Focus(); ///////////////////////////////////////////////////////////////////////////////// // Multiline TextBox: Actors this.labelActors = NewLabel(col[0] + 40, row[r], 18); this.labelActors.UseMnemonic = true; this.labelActors.Text = "&Actors"; this.labelActors.Height = Em.Height; this.actors = NewTextField(col[0] + 40, row[r + 1], 34); this.actors.Multiline = true; this.actors.Height = 5 * Em.Height + (Em.IsGUI ? 4 : 0); this.actors.AutoScrollBar = true; // Always move focus from actors label to actors field // this.labelActors.GotFocus += (source, e) => this.actors.Focus(); ///////////////////////////////////////////////////////////////////////////////// // Field validation event handlers this.movieTitle.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.movieTitle.ContentsChanged) { return; } ValidateNotNull("Movie title", this.movieTitle.Text, e); }; this.release.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.release.ContentsChanged) { return; } ValidateDate("First release (if specified)", this.release.Text, "yyyy-M-d", " in ISO format (yyyy-mm-dd).", e); }; this.duration.Validating += (sender, e) => { MdiForm.ErrorMessage = null; if (ReadOnly || !this.duration.ContentsChanged) { return; } string fieldName = "Duration in minutes, if specified,"; int fieldValue = 1; // default value to satisfy validation if null ValidateInteger(fieldName, this.duration.Text, e, ref fieldValue); // Duration must be either null or an integer >= 1 // if (!e.Cancel && fieldValue < 1) { MdiForm.ErrorMessage = fieldName + " must be greater than zero."; MdiForm.Beep(); e.Cancel = true; } else if (!e.Cancel && fieldValue > 24 * 60) { MdiForm.ErrorMessage = fieldName + " must be less than 24 hours."; MdiForm.Beep(); e.Cancel = true; } }; ///////////////////////////////////////////////////////////////////////////////// base.InitializeComponents(); }
///////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Validates the form (if validation is not suppressed by IgnoreRecordChanges) /// and returns true if it is safe to leave the form i.e. if changes done to the /// form record(s) are saved. /// </summary> /// private bool IsSafeToLeaveTheForm() { // User may always leave the form if changes were ignored or the record // is not modified (i.e. not dirty == clean). // if (IgnoreRecordChanges) { Debug.TraceLine("{0} Ignored Record Changes", TraceID); return(true); } bool contentsChanged = this.IsDirty(); if (!contentsChanged) { Debug.TraceLine("{0} Record is Clean", TraceID); return(true); } Debug.TraceLine("{0} Record is Dirty", TraceID); // Otherwise, we should ask user to commit changes... bool validationOK = true; MdiForm.ErrorMessage = Caption + " record has been modified..."; bool lostFocus = Em.IsGUI && MainForm.ActiveMdiChild != MdiForm; if (lostFocus) { MdiForm.Activate(); } DialogResult rc = MessageBox.Show("Do you want to save changes?", MdiForm.ErrorMessage, lostFocus ? MessageBoxButtons.YesNo : MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation); if (rc == DialogResult.Yes) { // Save record and catch any property violations // try { Debug.TraceLine("{0} Saving data...", TraceID); OnSaveData(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); validationOK = false; } if (validationOK && !ReadOnly) { SetReadOnly(true); } } else if (rc == DialogResult.No) { // Undo (cancel) changes // OnLoadData(); if (IsAddNew) { QuitForm(); } else if (!ReadOnly) { SetReadOnly(true); } } else // Cancel change of focus i.e. don't leave the form { validationOK = false; // This works in TextUI, however ... } // Clear our error message if user choosed to save/undo data // if (validationOK) { MdiForm.ErrorMessage = null; // refresh MDI status message } return(validationOK); }