用文件流 实现一个Winform程序,要求实现如下功能: 1)程序能够记忆位置 2)程序能够记忆大小
时间: 2024-02-05 07:11:12 浏览: 23
以下是一个简单的实现,使用了Windows API函数来实现记忆位置和大小的功能。程序使用文件流将位置和大小信息保存到本地文件中,以便下次启动时恢复窗口状态。
```csharp
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WinformPositionSizeMemory
{
public partial class Form1 : Form
{
private string _configFilePath = "config.ini";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadWindowState();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SaveWindowState();
}
private void LoadWindowState()
{
if (File.Exists(_configFilePath))
{
try
{
using (var streamReader = new StreamReader(_configFilePath))
{
var left = int.Parse(streamReader.ReadLine());
var top = int.Parse(streamReader.ReadLine());
var width = int.Parse(streamReader.ReadLine());
var height = int.Parse(streamReader.ReadLine());
SetWindowPos(Handle, IntPtr.Zero, left, top, width, height, SWP_NOZORDER);
}
}
catch (Exception ex)
{
MessageBox.Show($"Failed to load window state: {ex.Message}");
}
}
}
private void SaveWindowState()
{
try
{
using (var streamWriter = new StreamWriter(_configFilePath))
{
streamWriter.WriteLine(Left);
streamWriter.WriteLine(Top);
streamWriter.WriteLine(Width);
streamWriter.WriteLine(Height);
}
}
catch (Exception ex)
{
MessageBox.Show($"Failed to save window state: {ex.Message}");
}
}
#region Windows API
private const uint SWP_NOZORDER = 0x0004;
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
#endregion
}
}
```
在这个实现中,程序会在窗口加载时调用 `LoadWindowState()` 函数来读取之前保存的位置和大小信息,并调用 `SetWindowPos()` 函数来移动和调整窗口大小。当窗口关闭时,程序会调用 `SaveWindowState()` 函数来将当前窗口的位置和大小保存到本地文件中。在Windows API中,`SetWindowPos()` 函数可以用来移动和调整窗口大小,参数`SWP_NOZORDER`表示不改变窗口的Z顺序。
需要注意的是,这种方法只能保存窗口位置和大小,如果需要保存更多的状态信息,可以使用其他方法,比如序列化整个窗口对象。