public void AddForm(Form form)
        {
            if (_forms.ContainsKey(form.GetType()))
            {
                var formValues = _forms[form.GetType()];
                if (!formValues.Any(x => x == form))
                {
                    formValues.Add(form);
                }
            }
            else
            {
                _forms.Add(form.GetType(), new List<Form>() { form });
            }

            if (!_isPageRemovedEventAttached)
            {
                var pageTab = form.Parent as RadPageViewPage;
                if (pageTab != null)
                {
                    pageTab.Owner.PageRemoved += OwnerOnPageRemoved;
                }
                _isPageRemovedEventAttached = true;
            }
        }
示例#2
0
 Form addSubfomHelper_(Form par)
 {
     if(!windows_.ContainsKey(par.GetType()))
       {
     windows_.Add(par.GetType(),new ArrayList());
       }
       ArrayList storage = windows_[par.GetType()];
       storage.Add(par);
       return par;
 }
示例#3
0
        /// <summary>
        /// Set language for control
        /// </summary>
        /// <param name="lang"></param>
        public static void ChangeLanguage(string baseName, Assembly assembly, System.Windows.Forms.Form frm, Dictionary <object, string> lstControls, string lang, bool isSetCulture = true)
        {
            //Set Language Property
            Language = lang;
            //Set Language for Form Display
            if (isSetCulture)
            {
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
            }

            ComponentResourceManager resources = new ComponentResourceManager(frm.GetType());

            if (lstControls != null)
            {
                foreach (var ctrl in lstControls)
                {
                    var propertyInfo = ctrl.Key.GetType().GetProperty("Location");
                    if (propertyInfo != null)
                    {
                        var location = propertyInfo.GetValue(ctrl.Key, null);
                        resources.ApplyResources(ctrl.Key, ctrl.Value, new System.Globalization.CultureInfo(lang));
                        propertyInfo.SetValue(ctrl.Key, location, null);
                    }
                    else
                    {
                        resources.ApplyResources(ctrl.Key, ctrl.Value, new System.Globalization.CultureInfo(lang));
                    }
                }
            }

            resources = new ComponentResourceManager(frm.GetType().BaseType);

            if (lstControls != null && IsExistResource(resources, lstControls))
            {
                foreach (var ctrl in lstControls)
                {
                    var propertyInfo = ctrl.Key.GetType().GetProperty("Location");
                    if (propertyInfo != null)
                    {
                        var location = propertyInfo.GetValue(ctrl.Key, null);
                        resources.ApplyResources(ctrl.Key, ctrl.Value, new System.Globalization.CultureInfo(lang));
                        propertyInfo.SetValue(ctrl.Key, location, null);
                    }
                    else
                    {
                        resources.ApplyResources(ctrl.Key, ctrl.Value, new System.Globalization.CultureInfo(lang));
                    }
                }
            }

            //Set Language for Message
            SetMessageLanguage(baseName, assembly, lang);
        }
示例#4
0
 private static void LocalizeForm(Form frm)
 {
     var manager = new ComponentResourceManager(frm.GetType());
     manager.ApplyResources(frm, "$this");
     ApplyResources(manager, frm.Controls);
     
 }
 public static CtrlSettings GetSettings(Form form)
 {
     Lewis.SST.Settings.CtrlSettings cs = null;
     if (form != null)
     {
         try
         {
             cs = new Lewis.SST.Settings.CtrlSettings(form.GetType().ToString());
             if (typeof(Lewis.SST.Gui.Main).IsInstanceOfType(form))
             {
                 cs.LastDirectory = ((Lewis.SST.Gui.Main)form).LastDirectory;
             }
             cs.Name = form.Name;
             cs.Location = form.Location;
             cs.Size = form.Size;
             ArrayList arl = WalkControls(form.Controls);
             if (arl != null && arl.Count > 0)
             {
                 cs.ChildCtrlsToPersist = (Lewis.SST.Settings.CtrlSettings[])arl.ToArray(typeof(Lewis.SST.Settings.CtrlSettings));
             }
         }
         catch (Exception ex)
         {
             logger.Error(SQLSchemaTool.ERRORFORMAT, ex.Message, ex.Source, ex.StackTrace);
         }
     }
     return cs;
 }
		/// <summary>
		/// Instructs the listener to manage the specified form
		/// </summary>
		/// <param name="f">The form to manage</param>
		/// <param name="key">The key under which this form's settings will be saved</param>
		/// <param name="restore">A flag that indicates whether the form's state should be initially restored</param>
		/// <returns></returns>
		public bool Manage(Form f, string key, bool restore)
		{	
			// save the form reference		
			_form = f;
			_key  = key;
			_restore = restore;

			// format a path to this form's data
			_path = System.IO.Path.Combine(_path, f.GetType().FullName);
			_path = System.IO.Path.Combine(_path, key);
			
			// bind the the form's relevent events			
			f.Load += new EventHandler(OnLoad);
			f.SizeChanged += new EventHandler(OnSizeChanged);
			f.LocationChanged += new EventHandler(OnLocationChanged);
			f.Move += new EventHandler(OnMove);
			f.Closed += new EventHandler(OnClosed);

			// start out with updated information
			this.GleamWindowData();

			// if we need to
			if (restore && f.Visible)
			{
				// immediately restore the form's information
				this.ReadWindowData();
				this.ApplyWindowData();
			}
			return true;
		}
示例#7
0
文件: FormUtil.cs 项目: tonfranco/LR
        public static void InstanceFormChild(Form frmChild, Form frmParent, bool modal)
        {
            if (frmParent != null)
                foreach (var item in frmParent.MdiChildren)
                {
                    if (item.GetType() == frmChild.GetType())
                    {
                        frmChild.Focus();
                        frmChild.BringToFront();
                        frmChild.Activate();
                        return;
                    }
                }

            frmChild.ShowInTaskbar = false;

            if (modal)
            {
                frmChild.TopLevel = true;
                frmChild.ShowDialog();
            }
            else
            {
                if (frmParent != null)
                    frmChild.MdiParent = frmParent;

                frmChild.Show();
            }
        }
 public MobsModelChoice(Form Window, TextBox Form)
 {
     if (Window.GetType() == typeof(LoadNPCTemplate))
     {
         loadNPCTemplateWindow = Window as LoadNPCTemplate;
         NPCTemplateModelTextBox = Form;
         this.Text = "NPCTemplate Models Chooser";
     }
     else if (Window.GetType() == typeof(LoadMob))
     {
         loadMobWindow = Window as LoadMob;
         MobModelTextBox = Form;
         this.Text = "Mob Model Chooser";
     }
     InitializeComponent();
 }
示例#9
0
        private static void ProcessDeletion(Form AMainWindow, Int32 ALedgerNumber, string ALedgerNameAndNumber)
        {
            TVerificationResultCollection VerificationResult;
            MethodInfo method;

            if (!TRemote.MFinance.Setup.WebConnectors.DeleteLedger(ALedgerNumber, out VerificationResult))
            {
                MessageBox.Show(
                    string.Format(Catalog.GetString("Deletion of Ledger '{0}' failed"), ALedgerNameAndNumber) + "\r\n\r\n" +
                    VerificationResult.BuildVerificationResultString(),
                    Catalog.GetString("Deletion failed"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(
                    string.Format(Catalog.GetString("Ledger '{0}' has been deleted"), ALedgerNameAndNumber),
                    Catalog.GetString("Deletion successful"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            method = AMainWindow.GetType().GetMethod("ShowCurrentLedgerInfoInStatusBar");

            if (method != null)
            {
                method.Invoke(AMainWindow, new object[] { });
            }
        }
示例#10
0
        private static void ProcessDeletion(Form AMainWindow, Int64 AConferenceKey, string AConferenceName)
        {
            TVerificationResultCollection VerificationResult;
            MethodInfo method;

            if (!TRemote.MConference.Conference.WebConnectors.DeleteConference(AConferenceKey, out VerificationResult))
            {
                MessageBox.Show(
                    string.Format(Catalog.GetString("Deletion of Conference '{0}' failed"), AConferenceName) + "\r\n\r\n" +
                    VerificationResult.BuildVerificationResultString(),
                    Catalog.GetString("Deletion failed"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(
                    string.Format(Catalog.GetString("Conference '{0}' has been deleted"), AConferenceName),
                    Catalog.GetString("Deletion successful"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            method = AMainWindow.GetType().GetMethod("ShowCurrentConferenceInfoInStatusBar");

            if (method != null)
            {
                method.Invoke(AMainWindow, new object[] { });
            }
        }
示例#11
0
 public void MdiShow2(BaseForm frm)
 {
     try
     {
         System.Windows.Forms.Form[] mdiChildren = base.MdiChildren;
         for (int i = 0; i < mdiChildren.Length; i++)
         {
             System.Windows.Forms.Form form = mdiChildren[i];
             if (form.GetType().Equals(frm.GetType()))
             {
                 form.Activate();
                 form.Show();
                 frm.Dispose();
                 return;
             }
         }
         frm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
         frm.MdiParent     = this;
         frm.KeyPreview    = true;
         frm.Mainform      = this;
         frm.InitFeatureButton();
         frm.Show();
     }
     catch (System.Exception ex)
     {
         clsPublic.ShowException(ex, this.Text);
     }
 }
示例#12
0
文件: Helper.cs 项目: viticm/pap2
        /// <summary>
        /// 关闭窗体及其所有的属性中定义的窗体
        /// </summary>
        /// <param name="form">窗体</param>
        /// <returns>属性中定义的窗体是否已经全部关闭</returns>
        public static bool CloseAllWindows(Form form)
        {
            bool result = true;

            try // 获取属性的过程可能会产生异常
            {
                Type t = form.GetType();
                foreach (PropertyInfo pi in t.GetProperties()) // 用反射获取窗体的所有属性,并将属性窗体关闭
                {
                    object o = t.InvokeMember(pi.Name, BindingFlags.GetProperty, null, form, null);
                    if (o is Form) // 窗口属性
                    {
                        Form newForm = o as Form;
                        if (newForm != null)
                        {
                            newForm.Close();
                            if (!newForm.IsDisposed && newForm.Visible) // 部分窗口如表元编辑器,只隐藏没关闭,需要做特殊判断
                            {
                                result = false;
                                break;
                            }
                        }
                    }
                }
            }
            catch { } // 忽略异常

            if(result) // 所有窗体属性已经成功关闭
            {
                IntPtr ptr = FindWindow(null, form.Text);
                PostMessage(ptr, 0x10, IntPtr.Zero, null);
            }

            return result;
        }
示例#13
0
 static protected void RestoreWindow(Form aForm) {
     bool xShowForm = true;
     //http://social.msdn.microsoft.com/forums/en-US/winforms/thread/72b2edaf-0719-4d22-885e-48d643dc626b
     var x = Settings.DS.Window.FindByName(aForm.GetType().Name);
     if (x != null) {
         if (!x.IsLeftNull()) {
             aForm.Left = x.Left;
         }
         if (!x.IsTopNull()) {
             aForm.Top = x.Top;
         }
         if (!x.IsWidthNull()) {
             aForm.Width = x.Width;
         }
         if (!x.IsHeightNull()) {
             aForm.Height = x.Height;
         }
         // On load the often end up behind other apps, so we do this to force them up on first show
         if (!x.IsVisibleNull()) {
             // Technically we should do this if any size exists, generally
             // they should be all present or all missing. so we just use
             // this one attribute for now.
             aForm.StartPosition = FormStartPosition.Manual;
             xShowForm = x.Visible;
         }
     }
     if (xShowForm) {
         Show(aForm);
     }
 }
 public static void showFormInfo(Form form)
 {
     StringBuilder str = new StringBuilder();
     str.Append("Tên lớp: " + form.GetType().FullName);
     str.AppendLine();
     str.Append("Màn hình public: " + (form is IPublicForm ? "Có" : "Không"));
     HelpDebug.ShowString(str.ToString());
 }
示例#15
0
 public PFTableForm(Form parent)
 {
     InitializeComponent();
     if (parent.GetType() == typeof(ApplicationForm))
     {
         this.parent = parent as ApplicationForm;
     }
 }
示例#16
0
		public void RemoveForm(Form form)
		{
			var type = form.GetType();
			if (_allForms.ContainsKey(type) == false)
				return;

			_allForms[type].Remove(form);
		}
示例#17
0
		public void LocalizeControls(Form form)
		{
			XmlNode controlsNode = this.langDoc.SelectSingleNode("//" + form.Name + "/Controls");
			if(controlsNode == null)
			{
				return;
			}
			foreach(XmlNode node in controlsNode.ChildNodes)
			{
				if(node.HasChildNodes && node.FirstChild.NodeType != XmlNodeType.Text)
				{
					FieldInfo fi = form.GetType().GetField(
						node.Name,
						BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
					PropertyInfo items = fi.FieldType.GetProperty("Items");
					MethodInfo clear = items.PropertyType.GetMethod("Clear");
					clear.Invoke(items.GetValue(fi.GetValue(form),null),null);
					foreach(XmlNode itemNode in node.ChildNodes)
					{
						MethodInfo add = items.PropertyType.GetMethod("Add");
						object [] addParams = new object[1];
						addParams[0] = itemNode.InnerText;
						add.Invoke(items.GetValue(fi.GetValue(form),null),addParams);
					}
					if(node.Attributes["ToolTipText"] != null)
					{
						PropertyInfo pi = fi.FieldType.GetProperty("ToolTipText");
						pi.SetValue(fi.GetValue(form),node.Attributes["ToolTipText"].Value,null);
					}
				}
				else if(node.NodeType != XmlNodeType.Comment)
				{
					if(node.InnerText != string.Empty)
					{
						if(node.Name.ToUpper() == "SELF")
						{
							form.Text = node.InnerText;
						}
						else
						{
							FieldInfo fi = form.GetType().GetField(
								node.Name,
								BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
							PropertyInfo pi = fi.FieldType.GetProperty("Text");
							pi.SetValue(fi.GetValue(form),node.InnerText,null);
						}
					}
					if(node.Attributes["ToolTipText"] != null)
					{
						FieldInfo fi = form.GetType().GetField(
							node.Name,
							BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
						PropertyInfo pi = fi.FieldType.GetProperty("ToolTipText");
						pi.SetValue(fi.GetValue(form),node.Attributes["ToolTipText"].Value,null);
					}
				}
			}
		}
示例#18
0
 public BoardPrint()
 {
     window = new Form();
       Type con = window.GetType();
       PropertyInfo p = con.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
       p.SetValue(window, true, null);
       window.Size = new System.Drawing.Size(800, 800);
       window.Show();
 }
示例#19
0
 private System.Windows.Forms.OpenFileDialog GetOpenFileDialog(System.Windows.Forms.Form form)
 {
     System.Reflection.PropertyInfo propertyInfo = form.GetType().GetProperty("OpenFileDialog", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
     if (propertyInfo != null)
     {
         return(propertyInfo.GetValue(form, null) as System.Windows.Forms.OpenFileDialog);
     }
     return(null);
 }
 private static void refreshControlCulture(Control control, Form form)
 {
     ComponentResourceManager r = new ComponentResourceManager(form.GetType());
     r.ApplyResources(control, control.Name);
     foreach (Control c in control.Controls)
     {
         refreshControlCulture(c, form);
     }
 }
 public void RemoveForm(Form form)
 {
     var formList = GetFormsInternal(form.GetType());
     var formToRemove = formList.FirstOrDefault(x => x == form);
     if (formToRemove != null)
     {
         formList.Remove(form);
     }
 }
 public static void Translate(this MenuItem menuItem, Form form)
 {
     foreach (FieldInfo field in form.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance))
     {
         if (field.GetValue(form) == menuItem)
         {
             menuItem.Text = Translate(field.Name) ?? menuItem.Text;
             return;
         }
     }
 }
示例#23
0
 static protected void SaveWindow(Form aForm) {
     var x = Settings.DS.Window;
     var xRow = x.NewWindowRow();
     xRow.Name = aForm.GetType().Name;
     xRow.Left = aForm.Left;
     xRow.Top = aForm.Top;
     xRow.Width = aForm.Width;
     xRow.Height = aForm.Height;
     xRow.Visible = aForm.Visible;
     x.AddWindowRow(xRow);
 }
示例#24
0
        public static void ChangeCulture(Form frm, string cultureCode)
        {
            culture = CultureInfo.GetCultureInfo(cultureCode);

            Thread.CurrentThread.CurrentUICulture = culture;

            ComponentResourceManager resources = new ComponentResourceManager(frm.GetType());

            ApplyResourceToControl(resources, frm, culture);
            resources.ApplyResources(frm, "$this", culture);
        }
示例#25
0
 public static void SaveDesignForm(System.Windows.Forms.Form ctr)
 {
     UIMessage.DBEngine.exec("FormLayout_Save",
                             "@FormName", ctr.FindForm().Name,
                             "@ControlName", ctr.Name,
                             "@SystemType", string.Format("{0},{1}", ctr.GetType().FullName, ctr.GetType().Namespace),
                             "@LocationX", ctr.Location.X,
                             "@LocationY", ctr.Location.Y,
                             "@Height", ctr.Size.Height,
                             "@Width", ctr.Size.Width);
 }
示例#26
0
 public void MdiShow(BaseForm frm, object FuncId, bool ReStart = false)
 {
     try
     {
         System.Windows.Forms.Form[] mdiChildren = base.MdiChildren;
         for (int i = 0; i < mdiChildren.Length; i++)
         {
             System.Windows.Forms.Form form = mdiChildren[i];
             if (!ReStart)
             {
                 if (form.GetType().Equals(frm.GetType()))
                 {
                     form.Activate();
                     form.Show();
                     frm.Dispose();
                     return;
                 }
             }
             else if (form.GetType().Equals(frm.GetType()))
             {
                 form.Close();
                 form.Dispose();
             }
         }
         string objectString = clsPublic.GetObjectString(FuncId);
         if (!string.IsNullOrEmpty(objectString))
         {
             frm.sFuncId = Guid.Parse(objectString);
         }
         frm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
         frm.MdiParent     = this;
         frm.KeyPreview    = true;
         frm.Mainform      = this;
         frm.InitFeatureButton();
         frm.Show();
     }
     catch (System.Exception ex)
     {
         clsPublic.ShowException(ex, this.Text);
     }
 }
        public FormSettingsManager(Form form, string fileName)
        {
            var name = form.GetType().FullName + "-";
            _settings = Settings.Create(fileName, name);

            Load(form);

            form.Closed += (sender, e) =>
            {
                Save(form);
            };
        }
示例#28
0
 private void abreFormFilho(Form form)
 {
     foreach (Form formFilho in this.MdiChildren)
     {
         if (formFilho.GetType() == form.GetType())
         {
             formFilho.Focus();
             return;
         }
     }
     form.MdiParent = this;
     form.Show();
 }
示例#29
0
        public void setLocalization(Form targetForm)
        {
            if (xml.GetNode(targetForm.Name) == null) return;

            MemberInfo[] members = targetForm.GetType().GetMembers(
                                        BindingFlags.Public | BindingFlags.Instance);
            foreach (MemberInfo m in members)
            {
                if (m.MemberType == MemberTypes.Field)
                {
                    FieldInfo FType = targetForm.GetType().GetField(m.Name);
                    if (FType == null) continue;
                    if (FType.GetValue(targetForm) != null)
                    {
                        if (!FType.FieldType.FullName.StartsWith("System.Windows.Forms."))
                            continue;
                        string NodeName = targetForm.Name + "." + m.Name;
                        if (xml.GetNode(NodeName) != null)
                        {
                            if (FType.FieldType.FullName.EndsWith("Button"))
                                ((Button)FType.GetValue(targetForm)).Text = xml[NodeName];
                            else if (FType.FieldType.FullName.EndsWith("Label"))
                                ((Label)FType.GetValue(targetForm)).Text = xml[NodeName];
                            else if (FType.FieldType.FullName.EndsWith("ToolStripMenuItem"))
                                ((ToolStripMenuItem)FType.GetValue(targetForm)).Text = xml[NodeName];
                        }
                        else
                        {
                            if (FType.FieldType.FullName.EndsWith("Button"))
                                xml[NodeName] = ((Button)FType.GetValue(targetForm)).Text;
                            else if (FType.FieldType.FullName.EndsWith("Label"))
                                xml[NodeName] = ((Label)FType.GetValue(targetForm)).Text;
                            else if (FType.FieldType.FullName.EndsWith("ToolStripMenuItem"))
                                xml[NodeName] = ((ToolStripMenuItem)FType.GetValue(targetForm)).Text;
                        }
                    }
                }
            }
        }
示例#30
0
 private static IEnumerable<Button> getButtons(Form form)
 {
     var type = form.GetType().BaseType;
     var fields = type.GetFields(BindingFlags.Public
                                 | BindingFlags.NonPublic
                                 | BindingFlags.Instance
                                 | BindingFlags.DeclaredOnly);
     foreach (var button in fields.Where(f => typeof(Button).IsAssignableFrom(f.FieldType))
                                 .Select(f => f.GetValue(form) as Button))
     {
         yield return button;
     }
 }
示例#31
0
 //check Fomr MDI
 private void CheckMdiChildren(Form form)
 {
     foreach (Form frm in this.MdiChildren)
     {
         if (frm.GetType() == form.GetType())
         {
             frm.Focus();
             return;
         }
     }
     form.MdiParent = this;
     form.Show();
 }
示例#32
0
 private System.Object GetKeyForForm(System.Windows.Forms.Form AForm)
 {
     System.Object ReturnValue;
     try
     {
         ReturnValue = (System.Object)(AForm.GetType().ToString() + '_' + AForm.Handle.ToString());
     }
     catch (System.ObjectDisposedException)
     {
         // In case where the Form is already disposed by Windows we can't access
         // its Handle anymore, so just return the Type in this case.
         ReturnValue = AForm.GetType().ToString();
         MessageBox.Show(
             "TFormsList.GetKeyForForm: Form of Type '" + ReturnValue.ToString() + "' is already Disposed!" + "\r\n" +
             "This is a programmer error - a Form needs to be closed and removed from the FormsList before it may be Disposed!!!" + "\r\n" +
             "(Disposing is only necessary for Forms shown with ShowDialog.)", "DEVELOPER MESSAGE");
     }
     catch (Exception)
     {
         throw;
     }
     return(ReturnValue);
 }
示例#33
0
	/// <summary>
	/// Выполняет отображение MDIформы любого типа на родительской форме
	/// </summary>
	/// <param name="CurrentForm">Экземпляр отображаемой формы</param>
	public void ShowMDIForm(Form CurrentForm, object[] Params)
	{
		Type[] Types = new Type[0];
		if (Params != null) {
			Types = new Type[Params.Count()];
			for (int i = 0; i < Params.Count(); i++) {
				Types[i] = Params[i].GetType();
			}
		}
		System.Reflection.ConstructorInfo Constructor = CurrentForm.GetType().GetConstructor(Types);
		CurrentForm = (Form)Constructor.Invoke(Params);
		Parent.CurrentMenu.GetCurrentMenu().Enabled = false;
		Parent.CurrentDataTable.GetDataTable().Visible = false;
		CurrentForm.MdiParent = Parent;
		CurrentForm.Visible = false;
		System.Reflection.MethodInfo CheckBeforeShow = CurrentForm.GetType().GetMethod("CheckBeforeShow");
		if (CheckBeforeShow != null) {
			CheckBeforeShow.Invoke(CurrentForm, null);
		}
		else {
			CurrentForm.Show();
		}
	}	
示例#34
0
 /**
  * @desc It checks if the form is already opened, it it is, it shows it on top
  * @params [Form] The form to check
  * @return [bool] True if it is opened
  */
 public static bool bIsAlreadyOpened(Form frmMyForm)
 {
     foreach (Form frmOpenForm in Application.OpenForms)
     {
         if (frmOpenForm.GetType() == frmMyForm.GetType())
         {
             frmOpenForm.TopMost = true;
             frmOpenForm.Visible = true;
             frmOpenForm.Activate();
             return true;
         }
     }
     return false;
 }
示例#35
0
 /// <summary>
 /// 打開指定的窗體,如果已經實例化,則直接打開,否則先創建
 /// </summary>
 /// <param name="frm"></param>
 private void ShowWindow(System.Windows.Forms.Form frm)
 {
     foreach (Form mdiForm in this.MdiChildren)
     {
         if (mdiForm.GetType().Equals(frm.GetType()))
         {
             mdiForm.Activate();
             frm.Dispose();
             return;
         }
     }
     frm.MdiParent   = this;
     frm.WindowState = FormWindowState.Maximized;
     frm.Show();
 }
示例#36
0
        /// <summary>
        /// Saves form's location and size
        /// </summary>
        public static void Save(Form form)
        {
            string name = form.GetType().Name;

            // Only save geometry if the form state is normal (not maximized or minimized)
            if (form.WindowState == FormWindowState.Normal)
            {
                // Simply update our cache
                Geometry g = new Geometry {Location = form.Location, Size = form.Size};
                if (wnd.ContainsKey(name))
                    wnd[name] = g;
                else
                    wnd.Add(name, g);
            }
        }
示例#37
0
        protected PersistWindowState(Form window, string registrypath, bool allowSaveMinimized)
        {
            _window = window;
            _regPath = string.Format("{0}\\{1}", registrypath, window.GetType().Name);
            _allowSaveMinimized = allowSaveMinimized;

            // subscribe to form's events
            _window.Closing += new CancelEventHandler(OnClosing);
            _window.Resize += new EventHandler(OnResize);
            _window.Move += new EventHandler(OnMove);
            _window.Load += new EventHandler(OnLoad);
            _window.Closed += new EventHandler(OnClosed);

            // get initial width and height in case form is never resized
            _normalWidth = _window.Width;
            _normalHeight = _window.Height;
        }
示例#38
0
        //http://stackoverflow.com/questions/2820384/reading-embedded-xml-file-c-sharp#comment15356584_2820439
        //filename == namespace.folder.file.ext
        public static string GetResourceTextFile(
            System.Windows.Forms.Form oParent,
            string filename)
        {
            string sResult = "";

            using (Stream stream = oParent.GetType().Assembly.GetManifestResourceStream(filename))
            {
                //Read the stream
                using (StreamReader sr = new StreamReader(stream))
                {
                    sResult = sr.ReadToEnd();
                }
            }

            return(sResult);
        }
示例#39
0
        /// <summary>
        ///     Changes the language of the form.
        /// </summary>
        /// <param name="form">
        ///     <c>Form</c> object to apply changes to.
        /// </param>
        private void ChangeFormLanguage(System.Windows.Forms.Form form)
        {
            form.SuspendLayout();
            Cursor.Current = Cursors.WaitCursor;
            ResourceManager resources = new System.Resources.ResourceManager(form.GetType());

            // change main form resources
            form.Text = resources.GetString("$this.Text", m_cultureInfo);
            ReloadControlCommonProperties(form, resources);
            ToolTip toolTip = GetToolTip(form);

            // change text of all containing controls
            RecurControls(form, resources, toolTip);
            // change the text of menus
            ScanNonControls(form, resources);
            form.ResumeLayout();
        }
示例#40
0
        /// <summary>
        /// Set language for control
        /// </summary>
        /// <param name="lang"></param>
        private static void ChangeLanguage(string baseName, Assembly assembly, System.Windows.Forms.Form frm, string lang)
        {
            //Set Language Property
            Language = lang;
            //Set Language for Form Display
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
            CurrentLocale = Thread.CurrentThread.CurrentUICulture;

            foreach (Control c in frm.Controls)
            {
                ComponentResourceManager resources = new ComponentResourceManager(frm.GetType());
                resources.ApplyResources(c, c.Name, CurrentLocale);
                RefreshResources(frm, resources);
            }

            //Set Language for Message
            SetMessageLanguage(baseName, assembly, lang);
        }
示例#41
0
 /// <summary>
 ///     Scans controls that are not contained by <c>Controls</c>
 ///     collection, like <c>MenuItem</c>s, <c>StatusBarPanel</c>s
 ///     and <c>ColumnHeader</c>s.
 /// </summary>
 /// <param name="form">
 ///     <c>Form</c> object to scan.
 /// </param>
 /// <param name="resources">
 ///     <c>ResourceManager</c> used to get localized resources.
 /// </param>
 protected virtual void ScanNonControls(System.Windows.Forms.Form form, System.Resources.ResourceManager resources)
 {
     FieldInfo[] fieldInfo = form.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
     for (int i = 0; i < fieldInfo.Length; i++)
     {
         object o, obj = fieldInfo[i].GetValue(form);
         string fieldName = fieldInfo[i].Name;
         if (obj is System.Windows.Forms.MenuItem)
         {
             System.Windows.Forms.MenuItem menuItem = (System.Windows.Forms.MenuItem)obj;
             menuItem.Enabled      = (o = resources.GetObject(fieldName + ".Enabled", m_cultureInfo)) != null ? (bool)o : menuItem.Enabled;
             menuItem.Shortcut     = (o = resources.GetObject(fieldName + ".Shortcut", m_cultureInfo)) != null ? (Shortcut)o : menuItem.Shortcut;
             menuItem.ShowShortcut = (o = resources.GetObject(fieldName + ".ShowShortcut", m_cultureInfo)) != null ? (bool)o : menuItem.ShowShortcut;
             menuItem.Text         = resources.GetString(fieldName + ".Text", m_cultureInfo);
             menuItem.Visible      = (o = resources.GetObject(fieldName + ".Visible", m_cultureInfo)) != null ? (bool)o : menuItem.Visible;
         }
         if (obj is System.Windows.Forms.StatusBarPanel)
         {
             System.Windows.Forms.StatusBarPanel panel = (System.Windows.Forms.StatusBarPanel)obj;
             panel.Alignment   = (o = resources.GetObject(fieldName + ".Alignment", m_cultureInfo)) != null ? (HorizontalAlignment)o : panel.Alignment;
             panel.Icon        = (o = resources.GetObject(fieldName + ".Icon", m_cultureInfo)) != null ? (Icon)o : panel.Icon;
             panel.MinWidth    = (o = resources.GetObject(fieldName + ".MinWidth", m_cultureInfo)) != null ? (int)o : panel.MinWidth;
             panel.Text        = resources.GetString(fieldName + ".Text", m_cultureInfo);
             panel.ToolTipText = resources.GetString(fieldName + ".ToolTipText", m_cultureInfo);
             panel.Width       = (o = resources.GetObject(fieldName + ".Width", m_cultureInfo)) != null ? (int)o : panel.Width;
         }
         if (obj is System.Windows.Forms.ColumnHeader)
         {
             System.Windows.Forms.ColumnHeader header = (System.Windows.Forms.ColumnHeader)obj;
             header.Text      = resources.GetString(fieldName + ".Text", m_cultureInfo);
             header.TextAlign = (o = resources.GetObject(fieldName + ".TextAlign", m_cultureInfo)) != null ? (HorizontalAlignment)o : header.TextAlign;
             header.Width     = (o = resources.GetObject(fieldName + ".Width", m_cultureInfo)) != null ? (int)o : header.Width;
         }
         if (obj is System.Windows.Forms.ToolBarButton)
         {
             System.Windows.Forms.ToolBarButton button = (System.Windows.Forms.ToolBarButton)obj;
             button.Enabled     = (o = resources.GetObject(fieldName + ".Enabled", m_cultureInfo)) != null ? (bool)o : button.Enabled;
             button.ImageIndex  = (o = resources.GetObject(fieldName + ".ImageIndex", m_cultureInfo)) != null ? (int)o : button.ImageIndex;
             button.Text        = resources.GetString(fieldName + ".Text", m_cultureInfo);
             button.ToolTipText = resources.GetString(fieldName + ".ToolTipText", m_cultureInfo);
             button.Visible     = (o = resources.GetObject(fieldName + ".Visible", m_cultureInfo)) != null ? (bool)o : button.Visible;
         }
     }
 }
示例#42
0
 public bool PreFilterMessage(ref System.Windows.Forms.Message m)
 {
     try
     {
         if (!FoundResourcePickerDialog)
         {
             System.Windows.Forms.Form form = System.Windows.Forms.Control.FromHandle(m.HWnd) as System.Windows.Forms.Form;
             if ((form != null) && form.GetType().FullName.StartsWith("Microsoft.VisualStudio.Windows.Forms.ResourcePickerDialog"))
             {
                 AttachEvents(form);
             }
         }
     }
     catch (System.Exception e)
     {
         UIService.ShowError(e);
     }
     return(false);
 }
示例#43
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ADontCloseForm"></param>
        /// <returns></returns>
        public Boolean CloseAllExceptOne(System.Windows.Forms.Form ADontCloseForm)
        {
            System.Windows.Forms.Form FormInstance;
            IDictionaryEnumerator     DictEnum;

            System.Object OldKey;
            try
            {
                DictEnum = GetEnumerator();

                while (DictEnum.MoveNext())
                {
                    FormInstance = (System.Windows.Forms.Form)DictEnum.Value;
                    OldKey       = DictEnum.Key;

                    if ((ADontCloseForm == null) || (FormInstance.GetType() != ADontCloseForm.GetType()))
                    {
                        // MessageBox.Show('ADontCloseForm.GetType: ' + ADontCloseForm.GetType().ToString);
                        // MessageBox.Show('About to close Form: ' + FormInstance.GetType().ToString + '; Title: ' + FormInstance.Text);
                        FormInstance.Close();

                        // make sure the form really has been removed; otherwise it could be an endless loop
                        if (Dictionary.Contains(OldKey) == true)
                        {
                            Dictionary.Remove(OldKey);
                        }

                        /*
                         * Need to go back to the beginning of the enumerator because the Enumerator won't work
                         * anymore after a Form has been closed (when a Form closes it removes
                         * itself from the FormsList)!
                         */
                        DictEnum = GetEnumerator();
                    }
                }
            }
            catch (Exception Exp)
            {
                MessageBox.Show("TFormsList.CloseAll: Exception occured while trying to close forms: " + Exp.ToString());
                return(false);
            }
            return(true);
        }
 private void btnRoom_Add_Click(object sender, EventArgs e)
 {
     try
     {
         System.Collections.Hashtable htproperties = new System.Collections.Hashtable();
         htproperties.Add("Ngay_Batdau", dtNgay_Batdau.DateTime);
         htproperties.Add("Ngay_Ketthuc", dtNgay_Ketthuc.DateTime);
         System.Windows.Forms.Form dialog = GoobizFrame.Windows.MdiUtils.ThemeSettings.ShowExternalDialog("Ecm.Bar.dll",
                                                                                                          "Ecm.Bar.Forms.Rent.Frmbar_Rent_Reserve_RoomLookup", this, null, htproperties, false);
         if (dialog == null)
         {
             return;
         }
         var SelectedObject = dialog.GetType().GetProperty("SelectedRow").GetValue(dialog, null) as System.Data.DataRow;
         if (SelectedObject == null)
         {
             return;
         }
         var sdr = dsBar_Rent_Reserve_Table.Tables[0].Select(string.Format("Id_Table={0}", SelectedObject["Id_Table"]));
         if (sdr.Length == 0)
         {
             var ndr = dsBar_Rent_Reserve_Table.Tables[0].NewRow();
             ndr["Id_Reserve_Table"] = DateTime.Now.Ticks;
             ndr["Id_Reserve"]       = Current_Id_Reserve;
             ndr["Id_Table"]         = SelectedObject["Id_Table"];
             ndr["Guid_Reserve"]     = Current_Guid_Reserve;
             ndr["Ma_Table"]         = SelectedObject["Ma_Table"];
             ndr["Ten_Table"]        = SelectedObject["Ten_Table"];
             ndr["Ma_Class"]         = SelectedObject["Ma_Class"];
             ndr["Dongia"]           = SelectedObject["Dongia"];
             dsBar_Rent_Reserve_Table.Tables[0].Rows.Add(ndr);
             txtSoluong_Phong.EditValue = cvBar_Rent_Reserve_Table.RowCount;
         }
     }
     catch (Exception ex)
     {
         GoobizFrame.Windows.TrayMessage.TrayMessage.Status = new GoobizFrame.Windows.TrayMessage.TrayMessageInfo(MessageBoxIcon.Asterisk, ex.Message, ex.ToString());
     }
 }
 private string BuildPropertyName(string settingName)
 {
     return(_form.GetType().Name + "." + _form.Name + "." + settingName);
 }
示例#46
0
        /// <summary>
        /// Метод инициализации нового треда
        /// </summary>
        /// <param name="ПараметрТреда"></param>
        private static void СтартоватьТред(object ПараметрТреда)
        {
            // мы уже находимся в новом треде

            System.Windows.Forms.Form ГлавнаяФормаПотока = null;
            try
            {
                // берем домен текущего приложения
                AppDomain доменПриложения = System.Threading.Thread.GetDomain();
                // назначаем перехватчик необработанных исключений потока
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(ПотокиПриложения.ПриНеобработанномИсключенииПотока);



                if (ПараметрТреда is System.Windows.Forms.Form)
                {
                    ГлавнаяФормаПотока = ПараметрТреда as System.Windows.Forms.Form;
                }
                else if (ПараметрТреда is Type)
                {
                    Type типСтартовогоОбъекта = ПараметрТреда as Type;
                    if (типСтартовогоОбъекта == typeof(System.Windows.Forms.Form) ||
                        типСтартовогоОбъекта.IsSubclassOf(typeof(System.Windows.Forms.Form)))
                    {
                        ГлавнаяФормаПотока = Activator.CreateInstance(типСтартовогоОбъекта) as System.Windows.Forms.Form;
                    }
                    else if (типСтартовогоОбъекта.GetInterface("ИнтерфейсТочкиВходаПотока") != null)
                    {
                        object объектТочкиВходаПотока = Activator.CreateInstance(типСтартовогоОбъекта);
                        if (объектТочкиВходаПотока != null)
                        {
                            ГлавнаяФормаПотока = типСтартовогоОбъекта.InvokeMember("ТочкаВходаПотока", BindingFlags.InvokeMethod, null, объектТочкиВходаПотока, new object [] { }) as System.Windows.Forms.Form;
                        }
                    }
                }
                else if (ПараметрТреда.GetType().GetInterface("ИнтерфейсТочкиВходаПотока") != null)
                {
                    ГлавнаяФормаПотока = ПараметрТреда.GetType().InvokeMember("ТочкаВходаПотока", BindingFlags.InvokeMethod, null, ПараметрТреда, new object [] { }) as System.Windows.Forms.Form;
                }

                if (ГлавнаяФормаПотока == null)
                {
                    throw new ИсключениеБарсПриложения("Не удалось получить главную форму нового потока приложения.");
                }

                bool результатУстановкиПараметровОкна = false;

                try
                {
                    результатУстановкиПараметровОкна = ( bool )ГлавнаяФормаПотока.GetType().InvokeMember("УстановитьПараметрыОкна", BindingFlags.InvokeMethod, null, ГлавнаяФормаПотока, new string [] { "" });
                }
                catch (Exception)
                {
                    результатУстановкиПараметровОкна = true;
                }

                if (результатУстановкиПараметровОкна)
                {
                    // регистрируем окно в нашем реестре

                    НастольноеПриложение.ДобавитьТред(ГлавнаяФормаПотока, "");

                    ApplicationContext контексТреда = new ApplicationContext(ГлавнаяФормаПотока);

                    Application.Run(контексТреда);

                    Type тип = Type.GetType("Барс.Ядро.МенеджерБД,Ядро");
                    if (тип != null)
                    {
                        тип.InvokeMember("ОсвободитьРесурсыТреда", BindingFlags.InvokeMethod, null, null, null);
                    }
                }
            }
            catch (Exception exc)
            {
                ФормаПоказаИсключительнойСитуации.Показать(exc.Message, exc);
            }
            finally
            {
                if (ГлавнаяФормаПотока != null)
                {
                    НастольноеПриложение.ИсключитьТред();
                }
            }
        }
示例#47
0
        /// <summary>
        ///     Changes the language of the form.
        /// </summary>
        /// <param name="form">
        ///     <c>Form</c> object to apply changes to.
        /// </param>
        private void ChangeFormLanguage(System.Windows.Forms.Form form)
        {
            form.SuspendLayout();
            Cursor.Current = Cursors.WaitCursor;
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(form.GetType());
            // change main form resources
            form.Text = (string)(GetSafeValue(resources, "$this.Text", form.Text));
            ReloadControlCommonProperties(form, resources);

            // change text of all containing controls
            RecurControls(form, resources);
            // change the text of menus
            ScanNonControls(form, resources);

            Cursor.Current = Cursors.Default;

            form.ResumeLayout();
        }