用文件流 实现一个Winform程序,要求实现如下功能: 1)程序能够记忆位置 2)程序能够记忆大小;不构造函数
时间: 2024-02-05 18:12:03 浏览: 27
下面是一个实现以上要求的Winform程序,使用文件流来记录窗口位置和大小:
```csharp
using System;
using System.IO;
using System.Windows.Forms;
namespace RememberPositionAndSize
{
public partial class Form1 : Form
{
private const string SettingsFileName = "settings.txt";
public Form1()
{
InitializeComponent();
LoadSettings();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SaveSettings();
}
private void LoadSettings()
{
if (File.Exists(SettingsFileName))
{
try
{
using (var reader = new StreamReader(SettingsFileName))
{
var x = int.Parse(reader.ReadLine());
var y = int.Parse(reader.ReadLine());
var width = int.Parse(reader.ReadLine());
var height = int.Parse(reader.ReadLine());
if (x >= 0 && y >= 0 && width > 0 && height > 0)
{
DesktopBounds = new System.Drawing.Rectangle(x, y, width, height);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to load settings: " + ex.Message);
}
}
}
private void SaveSettings()
{
try
{
using (var writer = new StreamWriter(SettingsFileName))
{
writer.WriteLine(DesktopBounds.X);
writer.WriteLine(DesktopBounds.Y);
writer.WriteLine(DesktopBounds.Width);
writer.WriteLine(DesktopBounds.Height);
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to save settings: " + ex.Message);
}
}
}
}
```
在这个程序中,我们在窗口关闭前保存窗口位置和大小,并在下次打开程序时加载之前保存的窗口位置和大小。这些信息被保存在一个文本文件中,可以通过文件流读写。注意,我们并没有使用构造函数,而是在窗口加载时调用了 `LoadSettings` 方法来加载之前保存的设置。