【发布时间】:2021-12-27 03:05:01
【问题描述】:
我正在开发一个具有用作十六进制查看器的列表视图的应用程序,但存在重要的性能问题。我不是一个很有经验的程序员,所以我不知道如何优化代码。
这个想法是在将项目添加到列表视图时避免应用程序冻结。我在考虑或多或少地以 100 个项目为一组添加项目,但我不知道如何处理上下滚动,我不确定这是否能解决这些性能问题。
控件将始终具有相同的高度,即 795 像素。这是我正在使用的代码:
private void Button_SearchFile_Click(object sender, EventArgs e)
{
//Open files explorer.
OpenFileDialog_SearchFile.Filter = "SFX Files (*.sfx)|*.sfx";
DialogResult openEuroSoundFileDlg = OpenFileDialog_SearchFile.ShowDialog();
if (openEuroSoundFileDlg == DialogResult.OK)
{
//Get the selected file
string filePath = OpenFileDialog_SearchFile.FileName;
Textbox_FilePath.Text = filePath;
//Clear list.
ListView_HexEditor.Items.Clear();
//Start Reading.
using (BinaryReader BReader = new BinaryReader(File.OpenRead(filePath)))
{
//Each line will contain 16 bits.
byte[] bytesRow = new byte[16];
while (BReader.BaseStream.Position != BReader.BaseStream.Length)
{
//Get current offset.
long offset = BReader.BaseStream.Position;
//Read 16 bytes.
byte[] readedBytes = BReader.ReadBytes(16);
//Sometimes the last read could not contain 16 bits, with this we ensure to have a 16 bits array.
Buffer.BlockCopy(readedBytes, 0, bytesRow, 0, readedBytes.Length);
//Add item to the list.
ListView_HexEditor.Items.Add(new ListViewItem(new[]
{
//Print offset
offset.ToString("X8"),
//Merge bits
((bytesRow[0] << 8) | bytesRow[1]).ToString("X4"),
((bytesRow[2] << 8) | bytesRow[3]).ToString("X4"),
((bytesRow[4] << 8) | bytesRow[5]).ToString("X4"),
((bytesRow[6] << 8) | bytesRow[7]).ToString("X4"),
((bytesRow[8] << 8) | bytesRow[9]).ToString("X4"),
((bytesRow[10] << 8) | bytesRow[11]).ToString("X4"),
((bytesRow[12] << 8) | bytesRow[13]).ToString("X4"),
((bytesRow[14] << 8) | bytesRow[15]).ToString("X4"),
//Get hex ASCII representation
GetHexStringFormat(bytesRow)
}));
}
}
}
}
private string GetHexStringFormat(byte[] inputBytes)
{
//Get char in ascii encoding
char[] arrayChars = Encoding.ASCII.GetChars(inputBytes);
for (int i = 0; i < inputBytes.Length; i++)
{
//Replace no printable chars with a dot.
if (char.IsControl(arrayChars[i]) || (arrayChars[i] == '?' && inputBytes[i] != 63))
{
arrayChars[i] = '.';
}
}
return new string(arrayChars);
}
这是程序的图片:
【问题讨论】:
-
你的问题有点不清楚。您究竟在寻找什么?
-
您好!,简而言之,我们的想法是加载一个二进制文件,并在此列表视图中以十六进制格式显示它,而不会冻结应用程序,尽可能缩短时间。
-
是的,我知道你正在这样做,但是你的问题是什么?
-
如何避免将项目添加到列表视图时应用程序冻结
标签: c# winforms listview hex binaryfiles