您的位置:首页 > 编程语言 > C#

C#中实现窗体第二次打开时,在原来第一次关闭的位置,类似于QQ面板

2018-03-11 17:57 369 查看

第一步:新建一个FormPositionHelper.cs类 代码如下:

using Microsoft.Win32;//这个需加上
  
      class FormPositionHelper
      {
          // 在HKEY_CURRENT_USER 设置注册表的路径
          public static string RegPath = @"Software\App\";
          public static void SaveSize(System.Windows.Forms.Form frm)
          {
              //Create or retrieve a reference to a key where the settings
              //will be stored.
              RegistryKey key;
              key = Registry.LocalMachine.CreateSubKey(RegPath + frm.Name);
              key.SetValue("Height", frm.Height);
              key.SetValue("Width", frm.Width);
              key.SetValue("Left", frm.Left);
              key.SetValue("Top", frm.Top);
          }
          public static void SetSize(System.Windows.Forms.Form frm)
          {
              RegistryKey key;
              key=Registry.LocalMachine.OpenSubKey(RegPath+frm.Name);
              if(key!=null)
              {
              frm.Height=(int)key.GetValue("Height");
              frm.Width=(int)key.GetValue("Width");
              frm.Left=(int)key.GetValue("Left");
              frm.Top=(int)key.GetValue("Top");
              }
          }
       }


第二步:在窗体第一次加载和关闭之前调用上述类中的两个方法,具体如下:

//窗体加载事件
  private void Form1_Load(object sender, EventArgs e)
  {
      FormPositionHelper.SetSize(this);
  }
   //窗体关闭事件
  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  {
         
      if (this.WindowState != FormWindowState.Minimized) //必须加上这个判断,否则窗体最小化后无法恢复和还原了
          FormPositionHelper.SaveSize(this);
  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: