using EmreIstikam001.component.TehranOffice.ToosForAll;
using Rhino;
using Rhino.Display;
using Rhino.DocObjects;
using Rhino.FileIO;
using Rhino.Geometry;
using Rhino.Runtime.InProcess;
using Rhino.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmreIstikam001.component.TehranOffice.Components.Other.CustomLibrary
{
public partial class CustomLibraryFrm2 : Form
{
public event EventHandler PictureBoxClicked;
public event EventHandler PictureBoxDoubleClicked;
code
private volatile bool isCacheReady = false;
private PictureBox selectedPictureBox;
public DateTime selectTime = DateTime.Now;
private List<PictureBox> pictureBoxes = new List<PictureBox>();
private List<FileInfo> cachedFiles = new List<FileInfo>();
public string SelectedFilePath { get; private set; } = @"C:\PARDUS_CEPHE_YAZILIMI\Pardus_CY\01_BLOK\";
public string FileName { get; private set; }
public string UserPath { get; private set; }
int ColumnCount = 4;
int pictureBoxHeightSize = 150;
int pictureBoxWidthSize = 150;
int fixedSpacing = 10; // Fixed spacing between columns and rows
private ToolTip toolTip;
private string initialPath;
private Timer searchTimer;
private int currentSearchToken = 0;
public CustomLibraryFrm2()
{
InitializeComponent();
this.Resize += TableLayoutPanel01_Resize;
tableLayoutPanel01.Resize += TableLayoutPanel01_Resize;
initialPath = @"C:\PARDUS_CEPHE_YAZILIMI\Pardus_CY\01_BLOK";
InitializeGrid();
toolTip = new ToolTip();
SetPlaceholder();
lblSearching.Visible = false;
pictureBoxSearch.Visible = false;
// Subscribe to TreeView events
treeView1.BeforeExpand += TreeView1_BeforeExpand;
treeView1.AfterSelect += TreeView1_AfterSelect;
// Initialize ImageList for the TreeView
InitializeImageList();
SetPlaceholderLogin();
// Populate the TreeView
PopulateTreeView(initialPath);
// Initialize the search timer (set to 2 seconds)
searchTimer = new System.Windows.Forms.Timer();
searchTimer.Interval = 2000; // Set the debounce delay to 2000 milliseconds
searchTimer.Tick += SearchTimer_Tick;
// Start building the cache in the background
Task.Run(() => CacheAllFiles());
}
// Resize event handler
private void TableLayoutPanel01_Resize(object sender, EventArgs e)
{
AdjustColumnCount();
}
private void AdjustColumnCount()
{
// Calculate how many columns can fit in the current width of the TableLayoutPanel
if (tableLayoutPanel01.Width > 0)
{
int availableWidth = tableLayoutPanel01.Width - tableLayoutPanel01.Padding.Horizontal;
int pictureBoxWithSpacing = pictureBoxWidthSize + fixedSpacing;
int newColumnCount = Math.Max(1, availableWidth / pictureBoxWithSpacing);
ColumnCount = newColumnCount;
// Update the TableLayoutPanel and repopulate
UpdateTableLayout(newColumnCount);
}
}
private void UpdateTableLayout(int newColumnCount)
{
tableLayoutPanel01.Controls.Clear();
tableLayoutPanel01.RowStyles.Clear();
tableLayoutPanel01.ColumnStyles.Clear();
if (pictureBoxes.Count == 0) return;
int rowCount = (int)Math.Ceiling((double)pictureBoxes.Count / newColumnCount);
tableLayoutPanel01.RowCount = rowCount;
tableLayoutPanel01.ColumnCount = newColumnCount;
for (int i = 0; i < newColumnCount; i++)
{
tableLayoutPanel01.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, pictureBoxWidthSize));
}
for (int i = 0; i < rowCount; i++)
{
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Absolute, pictureBoxHeightSize + fixedSpacing));
}
// Populate controls with spacing
for (int i = 0; i < pictureBoxes.Count; i++)
{
int row = i / newColumnCount;
int col = i % newColumnCount;
tableLayoutPanel01.Controls.Add(pictureBoxes[i], col, row);
}
}
private void CacheAllFiles()
{
DirectoryInfo rootDirectory = new DirectoryInfo(initialPath);
// Begin caching files
List<FileInfo> allFiles = new List<FileInfo>();
GetAllFilesRecursive(rootDirectory, allFiles);
cachedFiles = allFiles;
// Set the cache ready flag
isCacheReady = true;
}
/// <summary>
/// Initializes the ImageList for the TreeView control.
/// </summary>
private void InitializeImageList()
{
ImageList imageList = new ImageList();
// Set the desired image size (e.g., 64x64 pixels)
imageList.ImageSize = new Size(25, 25);
// Add images to the image list
imageList.Images.Add("folder", Properties.Resources.noun_folder); // folder icon
imageList.Images.Add("file", Properties.Resources.kutuphane); // file icon
imageList.Images.Add("file3dm", Properties.Resources.PardusLogo1); // .3dm file icon
// Assign the ImageList to the TreeView
treeView1.ImageList = imageList;
//// Adjust the ItemHeight to accommodate larger images
//treeView1.ItemHeight = 70;
}
/// <summary>
/// Sets the placeholder text in the search TextBox.
/// </summary>
private void SetPlaceholder()
{
txtSearch.Text = "search...";
txtSearch.ForeColor = Color.Gray;
}
private void SetPlaceholderLogin()
{
txtUser.Text = "Staff ID...";
txtPass.Text = "Password...";
txtUser.ForeColor = Color.FromArgb(170, 170, 170);
txtPass.ForeColor = Color.FromArgb(170, 170, 170);
}
/// <summary>
/// Event handler for when the user enters the search TextBox.
/// </summary>
private void txtSearch_Enter(object sender, EventArgs e)
{
if (txtSearch.Text == "search...")
{
txtSearch.Text = "";
txtSearch.ForeColor = Color.Black;
}
}
/// <summary>
/// Event handler for when the user leaves the search TextBox.
/// </summary>
private void txtSearch_Leave(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtSearch.Text))
{
SetPlaceholder();
}
}
/// <summary>
/// Initializes the grid layout for displaying thumbnails.
/// </summary>
private void InitializeGrid()
{
tableLayoutPanel01.RowCount = 3;
tableLayoutPanel01.ColumnCount = 3;
tableLayoutPanel01.AutoScroll = true;
// Set the padding of the TableLayoutPanel
tableLayoutPanel01.Padding = new Padding(10); // Adjust the padding value as needed
tableLayoutPanel01.BackColor = Color.White; // Ensure the background is white
}
/// <summary>
/// Populates the TreeView with directories and files from the given root path.
/// Implements lazy loading for better performance.
/// </summary>
private void PopulateTreeView(string rootPath)
{
if (!Directory.Exists(rootPath))
{
string systemDriveRoot = Path.GetPathRoot(Environment.SystemDirectory);
string newFolderName = "PARDUS_CEPHE_YAZILIMI";
string newFolderPath = Path.Combine(systemDriveRoot, newFolderName);
if (!Directory.Exists(newFolderPath))
{
Directory.CreateDirectory(newFolderPath);
}
rootPath = newFolderPath;
}
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
TreeNode rootNode = new TreeNode(rootDirectory.Name)
{
Tag = rootDirectory,
ImageKey = "folder"
};
// Add a dummy node for lazy loading
rootNode.Nodes.Add(new TreeNode("Loading..."));
treeView1.Nodes.Add(rootNode);
rootNode.Expand();
//textBox1.Text = rootPath;
}
/// <summary>
/// Event handler for when a TreeView node is about to expand.
/// Implements lazy loading by loading subdirectories and files at this point.
/// </summary>
private void TreeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
TreeNode node = e.Node;
// Check if node contains a dummy "Loading..." node
if (node.Nodes.Count == 1 && node.Nodes[0].Text == "Loading...")
{
node.Nodes.Clear();
if (node.Tag is DirectoryInfo dir)
{
GetDirectories(dir, node);
}
}
}
/// <summary>
/// Recursively adds subdirectories and files to the TreeView node.
/// </summary>
private void GetDirectories(DirectoryInfo dir, TreeNode nodeToAddTo)
{
try
{
// Add subdirectories
DirectoryInfo[] subDirs = dir.GetDirectories();
foreach (DirectoryInfo subDir in subDirs)
{
TreeNode subNode = new TreeNode(subDir.Name)
{
Tag = subDir,
ImageKey = "folder"
};
// Add a dummy node for lazy loading
subNode.Nodes.Add(new TreeNode("Loading..."));
nodeToAddTo.Nodes.Add(subNode);
}
// Add files
//FileInfo[] files = dir.GetFiles();
//foreach (FileInfo file in files)
//{
// TreeNode fileNode = new TreeNode(file.Name)
// {
// Tag = file,
// ImageKey = file.Extension.Equals(".3dm", StringComparison.OrdinalIgnoreCase) ? "file3dm" : "file"
// };
// nodeToAddTo.Nodes.Add(fileNode);
//}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Access denied to {dir.FullName}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred accessing {dir.FullName}: {ex.Message}");
}
}
/// <summary>
/// Event handler for when a node in the TreeView is selected.
/// </summary>
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var selectedNode = e.Node;
FileName = selectedNode.Text;
if (selectedNode.Tag is DirectoryInfo selectedDirectory)
{
pictureBoxes.Clear();
PopulateTableWithThumbnails(selectedDirectory);
}
else if (selectedNode.Tag is FileInfo selectedFile)
{
SelectedFilePath = selectedFile.FullName;
// Clear existing controls
pictureBoxes.Clear();
tableLayoutPanel01.Controls.Clear();
tableLayoutPanel01.RowStyles.Clear();
tableLayoutPanel01.ColumnStyles.Clear();
tableLayoutPanel01.RowCount = 0;
tableLayoutPanel01.ColumnCount = 0;
tableLayoutPanel01.RowCount = 1;
tableLayoutPanel01.ColumnCount = 1;
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Percent, 800));
tableLayoutPanel01.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
// Create the PictureBox
PictureBox pictureBox = new PictureBox
{
Width = 1300,
Height = 1500,
SizeMode = PictureBoxSizeMode.Zoom,
Anchor = AnchorStyles.None,
Margin = new Padding(0),
Tag = selectedFile.FullName,
Cursor = Cursors.Hand,
};
// Load the thumbnail
try
{
Bitmap rhinoThumbnail = WindowsThumbnailProvider.GetThumbnail(selectedFile.FullName, 400, 600, ThumbnailOptions.InCacheOnly);
if (rhinoThumbnail != null)
{
pictureBox.Image = rhinoThumbnail;
}
else
{
// If no thumbnail is available, you can display a placeholder image
// pictureBox.Image = Properties.Resources.PlaceholderImage;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading thumbnail for {selectedFile.FullName}: {ex.Message}");
// Optionally display an error image
// pictureBox.Image = Properties.Resources.ErrorImage;
}
// Add the PictureBox to the tableLayoutPanel in the center cell
tableLayoutPanel01.Controls.Add(pictureBox, 0, 0);
pictureBoxes.Add(pictureBox);
}
// Remove existing event handlers to prevent multiple subscriptions
foreach (Control control in tableLayoutPanel01.Controls)
{
if (control is PictureBox pictureBox)
{
pictureBox.Click += PictureBox_Click;
pictureBox.Paint += PictureBox_Paint;
}
}
}
/// <summary>
/// Event handler for the "Browse" button click to select a custom directory.
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
if (fbd1.ShowDialog() == DialogResult.OK)
{
UserPath = fbd1.SelectedPath;
treeView1.Nodes.Clear();
PopulateTreeView(UserPath);
}
}
/// <summary>
/// Populates the TableLayoutPanel with thumbnails of the files in the given directory.
/// </summary>
public void PopulateTableWithThumbnails(DirectoryInfo directory)
{
// Clear existing data
pictureBoxes.Clear();
tableLayoutPanel01.Controls.Clear();
tableLayoutPanel01.RowStyles.Clear();
tableLayoutPanel01.ColumnStyles.Clear();
tableLayoutPanel01.RowCount = 0;
tableLayoutPanel01.ColumnCount = 0;
// Begin layout suspension
tableLayoutPanel01.SuspendLayout();
// Get files with .3dm extension
FileInfo[] files = directory.GetFiles()
.Where(f => f.Extension.Equals(".3dm", StringComparison.OrdinalIgnoreCase))
.ToArray();
int rowCount = (int)Math.Ceiling((double)files.Length / ColumnCount);
tableLayoutPanel01.RowCount = rowCount;
tableLayoutPanel01.ColumnCount = ColumnCount;
// Set up styles
for (int i = 0; i < ColumnCount; i++)
{
tableLayoutPanel01.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, pictureBoxWidthSize));
}
for (int i = 0; i < rowCount; i++)
{
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Absolute, 800));
}
tableLayoutPanel01.AutoSize = false;
tableLayoutPanel01.AutoScroll = true;
// Populate controls
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i];
PictureBox pictureBox = CreatePictureBoxForFile(file, pictureBoxWidthSize, pictureBoxHeightSize);
int row = i / ColumnCount;
int col = i % ColumnCount;
tableLayoutPanel01.Controls.Add(pictureBox, col, row);
pictureBoxes.Add(pictureBox);
}
// End layout suspension and refresh
tableLayoutPanel01.ResumeLayout();
tableLayoutPanel01.Refresh();
}
/// <summary>
/// Creates a PictureBox for the given file.
/// </summary>
private PictureBox CreatePictureBoxForFile(FileInfo file, int pictureBoxWidth, int pictureBoxHeight)
{
PictureBox pictureBox = new PictureBox
{
Width = pictureBoxWidth,
Height = pictureBoxHeight,
BorderStyle = BorderStyle.None,
SizeMode = PictureBoxSizeMode.StretchImage,
Cursor = Cursors.Hand,
BackColor = Color.LightGray,
Tag = file.FullName,
Margin = new Padding(5) // Adjust the margin value as needed
};
toolTip.SetToolTip(pictureBox, file.Name);
// Load thumbnail image
try
{
//Bitmap rhinoThumbnail = WindowsThumbnailProvider.GetThumbnail(file.FullName, pictureBoxWidth, pictureBoxHeight, ThumbnailOptions.InCacheOnly);
Bitmap rhinoThumbnail = File3dm.ReadPreviewImage(file.FullName);
if (rhinoThumbnail != null)
{
pictureBox.Image = rhinoThumbnail;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading thumbnail for {file.FullName}: {ex.Message}");
}
return pictureBox;
}
/// <summary>
/// Click event handler for PictureBox.
/// </summary>
private void PictureBox_Click(object sender, EventArgs e)
{
if (sender is PictureBox clickedPictureBox)
{
if ((DateTime.Now.Ticks - selectTime.Ticks) / 10000 < 300 && selectedPictureBox == clickedPictureBox)
{
//PictureBox_DoubleClick(sender, e);
// Raise the custom event
SelectedFilePath = clickedPictureBox.Tag.ToString();
FileName = Path.GetFileNameWithoutExtension(clickedPictureBox.Tag.ToString());
OnPictureBoxClicked(clickedPictureBox);
}
selectTime = DateTime.Now;
if (selectedPictureBox != null)
{
selectedPictureBox.BorderStyle = BorderStyle.None;
selectedPictureBox.Invalidate();
}
selectedPictureBox = clickedPictureBox;
selectedPictureBox.BorderStyle = BorderStyle.FixedSingle;
selectedPictureBox.Invalidate();
}
}
/// <summary>
/// Double-click event handler for PictureBox.
/// </summary>
private void PictureBox_DoubleClick(object sender, EventArgs e)
{
if (sender is PictureBox doubleClickedPictureBox)
{
SelectedFilePath = doubleClickedPictureBox.Tag.ToString();
// Raise the custom event
//OnPictureBoxDoubleClicked(doubleClickedPictureBox);
}
}
protected virtual void OnPictureBoxDoubleClicked(PictureBox clickedPictureBox)
{
PictureBoxDoubleClicked?.Invoke(this, new PictureBoxEventArgs(clickedPictureBox));
}
protected virtual void OnPictureBoxClicked(PictureBox clickedPictureBox)
{
PictureBoxClicked?.Invoke(this, new PictureBoxEventArgs(clickedPictureBox));
}
/// <summary>
/// Paint event handler for PictureBox to draw a border around the selected PictureBox.
/// </summary>
private void PictureBox_Paint(object sender, PaintEventArgs e)
{
if (sender is PictureBox picBox && picBox == selectedPictureBox)
{
var borderWidth = 10;
var borderColor = Color.CadetBlue;
Rectangle rect = new Rectangle(0, 0, picBox.Width - 3, picBox.Height - 3);
using (Pen pen = new Pen(borderColor, borderWidth))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
}
private async void SearchTimer_Tick(object sender, EventArgs e)
{
// Stop the timer
searchTimer.Stop();
// Capture the current search token
int searchToken = currentSearchToken;
// Perform the search asynchronously
await PerformSearchAsync(searchToken);
}
private async Task PerformSearchAsync(int searchToken)
{
// Ensure we're on the UI thread before updating UI controls
if (InvokeRequired)
{
Invoke(new Action(async () => await PerformSearchAsync(searchToken)));
return;
}
// Show the searching indicators
lblSearching.Visible = true;
pictureBoxSearch.Visible = true;
string searchText = txtSearch.Text.ToLower();
bool searchSubdirectories = chbSearchAll.Checked;
List<FileInfo> matchingFiles = null;
if (searchSubdirectories)
{
if (!isCacheReady)
{
// Cache is not ready
lblSearching.Text = "Building file cache, please wait...";
return;
}
// Perform search in the cache list on a background thread
matchingFiles = await Task.Run(() =>
{
return cachedFiles.Where(file => file.Name.ToLower().Contains(searchText)).ToList();
});
}
else
{
DirectoryInfo currentDirectory = GetCurrentSelectedDirectory();
if (currentDirectory == null)
{
// Remove "Searching..." label
tableLayoutPanel01.Controls.Clear();
// Only hide the indicators if this is the latest search
if (searchToken == currentSearchToken)
{
lblSearching.Visible = false;
pictureBoxSearch.Visible = false;
}
return;
}
// Perform search in current directory on a background thread
matchingFiles = await Task.Run(() =>
{
return SearchInCurrentDirectory(currentDirectory, searchText);
});
}
// Before updating the UI, check if this is still the latest search
if (searchToken != currentSearchToken)
{
// A newer search has started, do not update the UI or hide the indicators
return;
}
// Update the UI with the matching files
UpdatePictureBoxes(matchingFiles, searchToken);
// Hide the searching indicators
lblSearching.Visible = false;
pictureBoxSearch.Visible = false;
}
private DirectoryInfo GetCurrentSelectedDirectory()
{
if (treeView1.SelectedNode?.Tag is DirectoryInfo dir)
{
return dir;
}
else if (treeView1.SelectedNode?.Tag is FileInfo file)
{
return file.Directory;
}
else
{
return null;
}
}
// Recursive method to get all files
private void GetAllFilesRecursive(DirectoryInfo directory, List<FileInfo> allFiles)
{
try
{
allFiles.AddRange(directory.GetFiles()
.Where(file => file.Extension.Equals(".3dm", StringComparison.OrdinalIgnoreCase)));
foreach (DirectoryInfo subDir in directory.GetDirectories())
{
GetAllFilesRecursive(subDir, allFiles);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing {directory.FullName}: {ex.Message}");
}
}
private void ResetPictureBoxesToCurrentDirectory()
{
if (treeView1.SelectedNode?.Tag is DirectoryInfo selectedDirectory)
{
pictureBoxes.Clear();
PopulateTableWithThumbnails(selectedDirectory);
}
else if (treeView1.SelectedNode?.Tag is FileInfo selectedFile)
{
pictureBoxes.Clear();
PopulateTableWithThumbnails(selectedFile.Directory);
}
else
{
// Handle case when nothing is selected
pictureBoxes.Clear();
tableLayoutPanel01.Controls.Clear();
}
}
/// <summary>
/// Event handler for text changes in the search TextBox.
/// </summary>
private void txtSearch_TextChanged(object sender, EventArgs e)
{
string searchText = txtSearch.Text.ToLower();
if (searchText == "search..." || string.IsNullOrWhiteSpace(searchText))
{
// Reset the displayed PictureBoxes
ResetPictureBoxesToCurrentDirectory();
// Optionally, reset the search token
// currentSearchToken = 0;
return;
}
if (chbSearchAll.Checked && !isCacheReady)
{
// Show a message indicating that cache is being built
lblSearching.Text = "Building file cache, please wait...";
lblSearching.Visible = true;
pictureBoxSearch.Visible = true;
// Do not proceed with search until cache is ready
return;
}
// Clear the tableLayoutPanel01
tableLayoutPanel01.Controls.Clear();
lblSearching.Text = "Searching...";
lblSearching.Visible = true;
pictureBoxSearch.Visible = true;
// Increment the search token
currentSearchToken++;
// Restart the timer for debouncing
searchTimer.Stop();
searchTimer.Start();
}
/// <summary>
/// Searches for files containing the search text in the current directory.
/// </summary>
// Search only in the current directory
private List<FileInfo> SearchInCurrentDirectory(DirectoryInfo directory, string searchText)
{
try
{
var matchingFiles = directory.GetFiles()
.Where(file => file.Name.ToLower().Contains(searchText) &&
file.Extension.Equals(".3dm", StringComparison.OrdinalIgnoreCase))
.ToList();
return matchingFiles;
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred during search: {ex.Message}");
return new List<FileInfo>();
}
}
/// <summary>
/// Searches for files containing the search text recursively in all subdirectories.
/// </summary>
// Search recursively through all subdirectories
private List<FileInfo> SearchInAllDirectories(DirectoryInfo directory, string searchText)
{
List<FileInfo> matchingFiles = new List<FileInfo>();
GetMatchingFilesRecursive(directory, searchText, matchingFiles);
//UpdatePictureBoxes(matchingFiles);
return matchingFiles;
}
/// <summary>
/// Recursively gets matching files containing the search text.
/// </summary>
// Recursive method to get all matching files
private void GetMatchingFilesRecursive(DirectoryInfo directory, string searchText, List<FileInfo> matchingFiles)
{
try
{
matchingFiles.AddRange(directory.GetFiles()
.Where(file => file.Name.ToLower().Contains(searchText) &&
file.Extension.Equals(".3dm", StringComparison.OrdinalIgnoreCase)));
foreach (DirectoryInfo subDir in directory.GetDirectories())
{
GetMatchingFilesRecursive(subDir, searchText, matchingFiles);
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Access denied to directory: {directory.FullName}, {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred accessing {directory.FullName}: {ex.Message}");
}
}
/// <summary>
/// Updates the PictureBox controls with the matching files.
/// </summary>
// Updates the PictureBox controls with the matching files
private void UpdatePictureBoxes(List<FileInfo> matchingFiles, int searchToken)
{
if (searchToken != currentSearchToken)
{
// A newer search has started, do not update the UI
return;
}
if (InvokeRequired)
{
Invoke(new Action(() => UpdatePictureBoxes(matchingFiles, searchToken)));
return;
}
lblSearching.Visible = false;
pictureBoxSearch.Visible = false;
// Clear existing controls and styles
pictureBoxes.Clear();
tableLayoutPanel01.Controls.Clear();
tableLayoutPanel01.RowStyles.Clear();
tableLayoutPanel01.ColumnStyles.Clear();
tableLayoutPanel01.RowCount = 0;
tableLayoutPanel01.ColumnCount = 0;
// Begin layout suspension
tableLayoutPanel01.SuspendLayout();
if (matchingFiles.Count == 0)
{
// Display "No files found" message
tableLayoutPanel01.RowCount = 1;
tableLayoutPanel01.ColumnCount = 1;
tableLayoutPanel01.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Percent, 800));
Label noResultsLabel = new Label()
{
Text = "No files found.",
AutoSize = true,
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleCenter
};
tableLayoutPanel01.Controls.Add(noResultsLabel, 0, 0);
}
else
{
int rowCount = (int)Math.Ceiling((double)matchingFiles.Count / ColumnCount);
tableLayoutPanel01.RowCount = rowCount;
tableLayoutPanel01.ColumnCount = ColumnCount;
// Set up styles
for (int i = 0; i < ColumnCount; i++)
{
tableLayoutPanel01.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, pictureBoxWidthSize));
}
for (int i = 0; i < rowCount; i++)
{
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Absolute, 800));
}
tableLayoutPanel01.AutoSize = false;
tableLayoutPanel01.AutoScroll = true;
// Populate controls
for (int i = 0; i < matchingFiles.Count; i++)
{
FileInfo file = matchingFiles[i];
PictureBox pictureBox = CreatePictureBoxForFile(file, pictureBoxWidthSize, pictureBoxHeightSize);
int row = i / ColumnCount;
int col = i % ColumnCount;
tableLayoutPanel01.Controls.Add(pictureBox, col, row);
pictureBoxes.Add(pictureBox);
}
}
// Remove existing event handlers to prevent multiple subscriptions
foreach (Control control in tableLayoutPanel01.Controls)
{
if (control is PictureBox pictureBox)
{
pictureBox.Click += PictureBox_Click;
pictureBox.Paint += PictureBox_Paint;
}
}
// End layout suspension and refresh
tableLayoutPanel01.ResumeLayout();
tableLayoutPanel01.Refresh();
}
/// <summary>
/// Custom event arguments for PictureBox events.
/// </summary>
public class PictureBoxEventArgs : EventArgs
{
public PictureBox ClickedPictureBox { get; set; }
public PictureBoxEventArgs(PictureBox pictureBox)
{
ClickedPictureBox = pictureBox;
}
}
private void txtUser_Enter(object sender, EventArgs e)
{
if (txtUser.Text == "Staff ID...")
{
txtUser.Text = "";
txtUser.ForeColor = Color.FromArgb(86, 106, 127);
}
}
private void txtUser_Leave(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtUser.Text))
{
txtUser.Text = "Staff ID...";
txtUser.ForeColor = Color.FromArgb(170, 170, 170);
}
}
private void txtPass_Enter(object sender, EventArgs e)
{
if (txtPass.Text == "Password...")
{
txtPass.Text = "";
txtPass.ForeColor = Color.FromArgb(86, 106, 127);
}
}
private void txtPass_Leave(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtPass.Text))
{
txtPass.Text = "Password...";
txtPass.ForeColor = Color.FromArgb(170, 170, 170);
}
}
private void lblSearching_Click(object sender, EventArgs e)
{
}
}
}
this is my code.
is it possible to add a lable under each picture box that its text is the image's tag
but the importent thing is that the rows should be distanced enough that the lables feet in between and this distance is fixed for all rows and if a labele text is more than the picture box with it sould replace the rest of it with"...".
Assistant
You can achieve this by modifying your PopulateTableWithThumbnails and UpdatePictureBoxes methods to include a Panel for each image and its corresponding label. This Panel will hold both the PictureBox and the Label, and you can adjust the layout to ensure sufficient space between rows based on your requirements. Let's walk through how this can be accomplished:
1. Modify CreatePictureBoxForFile Method
You will create a method to wrap a PictureBox inside a Panel with a Label below it for the file name.
csharp
private Panel CreatePictureBoxWithLabel(FileInfo file, int pictureBoxWidth, int pictureBoxHeight)
{
// Create Panel to hold PictureBox and Label
Panel panel = new Panel
{
Width = pictureBoxWidth,
Height = pictureBoxHeight + 30, // Adjust height to include space for label
Margin = new Padding(5),
AutoSize = false
};
// Create PictureBox
PictureBox pictureBox = new PictureBox
{
Width = pictureBoxWidth,
Height = pictureBoxHeight,
BorderStyle = BorderStyle.None,
SizeMode = PictureBoxSizeMode.StretchImage,
Cursor = Cursors.Hand,
BackColor = Color.LightGray,
Tag = file.FullName
};
// Load thumbnail image
try
{
Bitmap rhinoThumbnail = File3dm.ReadPreviewImage(file.FullName);
if (rhinoThumbnail != null)
{
pictureBox.Image = rhinoThumbnail;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading thumbnail for {file.FullName}: {ex.Message}");
}
// Create Label
Label label = new Label
{
Text = GetTruncatedFileName(file.Name, pictureBoxWidth), // Truncate if necessary
Dock = DockStyle.Bottom,
TextAlign = ContentAlignment.MiddleCenter,
AutoSize = false,
Width = pictureBoxWidth
};
// Add PictureBox and Label to Panel
panel.Controls.Add(pictureBox);
panel.Controls.Add(label);
// Add tooltip to PictureBox for full filename
toolTip.SetToolTip(pictureBox, file.Name);
return panel;
}
// Helper method to truncate file name if too long
private string GetTruncatedFileName(string fileName, int maxWidth)
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
Font font = new Font("Microsoft Sans Serif", 8.25F);
SizeF size = g.MeasureString(fileName, font);
if (size.Width > maxWidth)
{
// Calculate how many characters fit in the maxWidth minus some buffer for the "..."
int charCount = (int)(fileName.Length * (maxWidth / size.Width)) - 3;
return fileName.Substring(0, charCount) + "...";
}
return fileName;
}
}
User
Ensure that your row heights are tall enough to accommodate both the PictureBox and the Label
Assistant
To ensure that the row heights in the TableLayoutPanel can accommodate both the PictureBox and the Label, you'll need to adjust the row height settings based on the combined height of the controls you're placing in each cell. Here’s how you can make these adjustments:
Step-by-Step Guide
Calculate Total Height for Each Item
Determine the total height required for each item, which includes both the PictureBox and the Label. Add extra spacing if necessary to ensure clarity and separation between rows.
csharp
int pictureBoxHeightSize = 150;
int labelHeight = 30; // Adjust the height based on your font size and padding needs
int totalItemHeight = pictureBoxHeightSize + labelHeight + fixedSpacing; // fixedSpacing is to maintain a consistent spacing between rows
Update Row Height in PopulateTableWithThumbnails and UpdatePictureBoxes
When setting up your TableLayoutPanel, ensure you account for the total item height in your row definitions.
csharp
for (int i = 0; i < rowCount; i++)
{
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Absolute, totalItemHeight));
}
Adjust Layout Methods
In your layout methods (PopulateTableWithThumbnails and UpdatePictureBoxes), make sure you are placing each Panel as a unit into the TableLayoutPanel. This panel will automatically handle the layout of the PictureBox and Label.
csharp
User
in this new way how capture the mouse cliked and double clicked on the picture boxes in panels?
Assistant
To capture mouse click and double-click events on PictureBox controls that are placed within Panel controls, you need to attach the event handlers to the PictureBox itself. Even though the PictureBox is inside the Panel, you can still assign event listeners directly to the PictureBox. Here's how you would do it:
Step-by-Step Implementation
Attach Event Handlers to PictureBox within the CreatePictureBoxWithLabel Method
When you create the PictureBox, add event handlers for both Click and DoubleClick events.
csharp
private Panel CreatePictureBoxWithLabel(FileInfo file, int pictureBoxWidth, int pictureBoxHeight)
{
// Panel setup
Panel panel = new Panel
{
Width = pictureBoxWidth,
Height = pictureBoxHeight + 30, // Adjust height to include space for label
Margin = new Padding(5),
AutoSize = false
};
// PictureBox setup
PictureBox pictureBox = new PictureBox
{
Width = pictureBoxWidth,
Height = pictureBoxHeight,
BorderStyle = BorderStyle.None,
SizeMode = PictureBoxSizeMode.StretchImage,
Cursor = Cursors.Hand,
BackColor = Color.LightGray,
Tag = file.FullName
};
// Event handlers for PictureBox
pictureBox.Click += PictureBox_Click;
pictureBox.DoubleClick += PictureBox_DoubleClick;
// Load thumbnail image
try
{
Bitmap rhinoThumbnail = File3dm.ReadPreviewImage(file.FullName);
if (rhinoThumbnail != null)
{
pictureBox.Image = rhinoThumbnail;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading thumbnail for {file.FullName}: {ex.Message}");
}
// Label setup
Label label = new Label
{
Text = GetTruncatedFileName(file.Name, pictureBoxWidth),
Dock = DockStyle.Bottom,
TextAlign = ContentAlignment.MiddleCenter,
AutoSize = false,
Width = pictureBoxWidth
};
// Adding controls to the panel
panel.Controls.Add(pictureBox);
panel.Controls.Add(label);
// Add tooltip to pictureBox for full filename
toolTip.SetToolTip(pictureBox, file.Name);
return panel;
}
User
instead of one line label and puting "..." at the end of it
I want to make it two line and if still at the end of picture box with there is anything left of the text replace it with "..."
Assistant
If you'd like to make the label display two lines of text and truncate with "..." if necessary, you'll need to adjust the label's settings so it can handle multiline text and implement logic to properly truncate the text. Below is a step-by-step guide on how to achieve this:
Steps to Implement a Two-Line Label with Truncation
Setup the Label for Multiline Display
You need to configure your label to handle multiline text and manage its size and behavior properly.
Adjust the Method to Create and Truncate Text
Modify your CreatePictureBoxWithLabel method to support multiline text and truncation.
csharp
User
I want to remove any ".3dm" if there is in the label taxt
Assistant
To remove the ".3dm" file extension from the label text, you can simply modify the text handling logic to strip the extension before processing it for display. You can do this directly in the GetMultilineTruncatedText method before formatting the string. Here's how you can modify the method to achieve this:
Modified Method to Remove ".3dm" Extension
The idea is to check if the string ends with ".3dm" and remove it if found before proceeding with truncating or displaying the text.
csharp
private string GetMultilineTruncatedText(string text, int maxWidth)
{
// Remove ".3dm" extension if present
if (text.EndsWith(".3dm", StringComparison.OrdinalIgnoreCase))
{
text = text.Substring(0, text.Length - 4); // Remove the last 4 characters
}
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
Font font = new Font("Microsoft Sans Serif", 8.25F);
StringFormat format = new StringFormat
{
Trimming = StringTrimming.EllipsisCharacter,
FormatFlags = StringFormatFlags.LineLimit
};
// Measure the complete text block with allowance for two lines
SizeF size = g.MeasureString(text, font, new SizeF(maxWidth, font.Height * 2), format);
if (size.Height <= font.Height * 2)
{
return text;
}
// Attempt to fit text in specified width and height
Rectangle layoutRectangle = new Rectangle(Point.Empty, new Size(maxWidth, font.Height * 2));
CharacterRange[] ranges = { new CharacterRange(0, text.Length) };
format.SetMeasurableCharacterRanges(ranges);
Region[] regions = g.MeasureCharacterRanges(text, font, layoutRectangle, format);
RectangleF bounds = regions[0].GetBounds(g);
int fittingChars = g.MeasureString(text, font, new SizeF(maxWidth, font.Height * 2), format).ToString().Length;
return text.Substring(0, fittingChars) + "...";
}
}
The error message "System.ComponentModel.Win32Exception: 'Error creating window handle.'" typically indicates that your application is running out of available window handles. This can happen if there are too many controls being created in your application, or if controls are not being disposed of properly, leading to resource exhaustion. Here are some tips to address this issue:
Causes and Solutions
Too Many Controls:
Cause: If you're creating a very large number of controls (e.g., PictureBox, Panel, etc.), this can lead to exhaustion of system resources.
Solution: Consider virtualizing your controls so that only the controls currently visible are created. You might consider using a UI virtualization technique or a control like DataGridView or ListView in a virtual mode.
Not Disposing of Controls Properly:
Cause: If controls are not properly disposed of when they are no longer needed, they can remain in memory and continue to take up resources.
Solution: Ensure that you're calling Dispose on your controls appropriately. If you're dynamically creating controls, make sure they are disposed of when removed from the UI. You can use a using statement or explicitly call Dispose.
Memory Leaks:
Cause: Some memory leak scenarios can lead to handle exhaustion.
Solution: Use memory profiling tools to check for leaks, and ensure that event handlers and other references to disposable resources are managed correctly.
Too Many Nested Controls:
Cause: Deep nesting of controls can also cause excessive handle usage.
Solution: Flatten your control hierarchy where possible and reduce unnecessary nesting.
Use Efficient Methods for Image Display:
Cause: Displaying a large number of images can use up a lot of resources.
Solution: Consider more efficient ways to handle images, such as using an ImageList for small images or implementing a custom drawing technique if you need to render complex visuals.
Example: Dispose Controls Properly
If you're dynamically adding controls, make sure to dispose of them properly:
User
how can I do this in my code?
Solution: Consider virtualizing your controls so that only the controls currently visible are created. You might consider using a UI virtualization technique or a control like DataGridView or ListView in a virtual mode.
Assistant
Virtualizing your controls involves only creating and managing the UI elements that are currently visible to the user. As the user scrolls, you recycle existing controls and update them with new data, rather than creating new controls for every single item. This is especially important for applications displaying large data sets.
In Windows Forms, true virtualization is not as straightforward to implement as in frameworks like WPF. However, you can approximate virtualization using controls like ListView in virtual mode or by custom implementing a virtualizing panel. Here's how you might go about it:
Using ListView in Virtual Mode
ListView in virtual mode allows you to handle large sets of data by only dealing with the items currently visible. You'll need to provide the data on demand.
Step-by-Step Guide
Configure the ListView for Virtual Mode
Set the ListView to virtual mode and handle the RetrieveVirtualItem event. This event will provide the data for each item as it is needed.
csharp
listView1.VirtualMode = true;
listView1.VirtualListSize = totalNumberOfItems; // This should be your total data count
listView1.RetrieveVirtualItem += listView1_RetrieveVirtualItem;
Handle the RetrieveVirtualItem Event
In this event handler, provide the data for each item as requested by the ListView.
csharp
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
// Assuming you have a list of FileInfo objects
FileInfo file = yourFileList[e.ItemIndex];
ListViewItem item = new ListViewItem(file.Name);
// Optionally, add sub-items or images to the ListView item
// item.SubItems.Add(...);
// item.ImageIndex = ...;
e.Item = item;
}
Optimize for Performance
Ensure your ListView is set to a view that supports virtual mode effectively, such as View.Details.
Use a if you need sorting; avoid direct sort calls which can be performance intensive.
User
implement it to my entire code
Assistant
Implementing virtual mode in your application using ListView or similar controls requires some changes in how you manage and display your data. I'll demonstrate how you can transition your approach from using TableLayoutPanel with many PictureBox elements to a ListView with virtual mode support. This example will show you how to set up the list view to efficiently handle large data sets like your .3dm files.
Step-by-Step Implementation
Replace TableLayoutPanel with ListView:
First, replace your TableLayoutPanel with a ListView in your form designer. Make sure to set the ListView to virtual mode.
csharp
ListView listView1 = new ListView
{
Dock = DockStyle.Fill,
View = View.LargeIcon, // or View.Details, depending on your preference
VirtualMode = true,
VirtualListSize = 0 // This will be updated with the actual number of items
};
Handle the RetrieveVirtualItem Event:
Set up an event handler for RetrieveVirtualItem to supply data for each visible item.
2. Update PopulateTableWithThumbnails and UpdatePictureBoxes Methods
Use the new CreatePictureBoxWithLabel method to add panels containing both the PictureBox and the Label to your TableLayoutPanel.
Modify the PopulateTableWithThumbnails method:
csharp
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i];
Panel panel = CreatePictureBoxWithLabel(file, pictureBoxWidthSize, pictureBoxHeightSize);
int row = i / ColumnCount;
int col = i % ColumnCount;
tableLayoutPanel01.Controls.Add(panel, col, row);
pictureBoxes.Add(panel.Controls.OfType<PictureBox>().FirstOrDefault());
}
Similarly, modify the UpdatePictureBoxes method:
csharp
for (int i = 0; i < matchingFiles.Count; i++)
{
FileInfo file = matchingFiles[i];
Panel panel = CreatePictureBoxWithLabel(file, pictureBoxWidthSize, pictureBoxHeightSize);
int row = i / ColumnCount;
int col = i % ColumnCount;
tableLayoutPanel01.Controls.Add(panel, col, row);
pictureBoxes.Add(panel.Controls.OfType<PictureBox>().FirstOrDefault());
}
Adjust Row Height
Ensure that your row heights are tall enough to accommodate both the PictureBox and the Label. You need to adjust the row height in your layouts to provide adequate space based on the total height of the Panel holding the PictureBox and Label.
This setup should create a layout where each image has a corresponding label beneath it, with appropriately managed spacing and truncation, using a fixed-width approach.
private void PopulateTableWithThumbnails(DirectoryInfo directory)
{
// Clear existing data
pictureBoxes.Clear();
tableLayoutPanel01.Controls.Clear();
tableLayoutPanel01.RowStyles.Clear();
tableLayoutPanel01.ColumnStyles.Clear();
// Calculate number of rows required
int rowCount = (int)Math.Ceiling((double)files.Length / ColumnCount);
tableLayoutPanel01.RowCount = rowCount;
tableLayoutPanel01.ColumnCount = ColumnCount;
// Set the column width
for (int i = 0; i < ColumnCount; i++)
{
tableLayoutPanel01.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, pictureBoxWidthSize + fixedSpacing));
}
// Set the row height
for (int i = 0; i < rowCount; i++)
{
tableLayoutPanel01.RowStyles.Add(new RowStyle(SizeType.Absolute, totalItemHeight));
}
// Populate controls
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i];
Panel panel = CreatePictureBoxWithLabel(file, pictureBoxWidthSize, pictureBoxHeightSize);
int row = i / ColumnCount;
int col = i % ColumnCount;
tableLayoutPanel01.Controls.Add(panel, col, row);
pictureBoxes.Add(panel.Controls.OfType<PictureBox>().FirstOrDefault());
}
}
Key Points to Keep in Mind
Consistency in Layout: Make sure that your tableLayoutPanel01 setup remains consistent across your application. Any dynamic adjustment should consistently follow the spacing patterns you establish here.
Handling Dynamic Resizing: If the Form or TableLayoutPanel is dynamically resized (due to user action or programmatically), make sure you recalculate and adjust based on the new size using relevant resize event handlers.
By structuring your controls in this manner, and ensuring that your row height accommodates the combined size of the PictureBox and Label, your UI should reliably display all elements as intended, regardless of data set size or visual adjustments.
Implement Click and DoubleClick Event Handlers
Define your event handlers to actually perform operations when a PictureBox is clicked or double-clicked.
csharp
private void PictureBox_Click(object sender, EventArgs e)
{
if (sender is PictureBox clickedPictureBox)
{
// Handle the single click event
Console.WriteLine($"Single clicked: {clickedPictureBox.Tag}");
// Example: Highlight the selected picture box
clickedPictureBox.BorderStyle = BorderStyle.Fixed3D;
// You can reset other PictureBoxes' styles if needed
foreach (PictureBox pb in pictureBoxes)
{
if(!pb.Equals(clickedPictureBox))
{
pb.BorderStyle = BorderStyle.None;
}
}
}
}
private void PictureBox_DoubleClick(object sender, EventArgs e)
{
if (sender is PictureBox doubleClickedPictureBox)
{
// Handle the double click event
Console.WriteLine($"Double clicked: {doubleClickedPictureBox.Tag}");
// Example: Open the file or perform another action
Process.Start("explorer.exe", doubleClickedPictureBox.Tag.ToString());
}
}
Some Notes
Distinguishing Between Single and Double Clicks: When working with single and double click events, it's important to ensure that the single click event doesn't trigger undesired double click actions. Handling these events correctly might sometimes require additional logic if one affects the perception of the other (e.g., firing single click before double click is completed). .NET handles these reasonably in most cases, but complex scenarios may require extra debounce logic or state management.
Event Propagation: Since events bubble from PictureBox to Panel, then Form, and so forth, make sure you aren't accidentally handling events at multiple levels which might interfere with intended behavior.
User Experience: Confirm that your UI remains usable with these interactions, such as providing visual feedback on selected items or actions, and ensure accessibility requirements if applicable.
This setup captures clicks and double-clicks effectively on image PictureBox controls wrapped within panels in your layout.
private Panel CreatePictureBoxWithLabel(FileInfo file, int pictureBoxWidth, int pictureBoxHeight)
{
// Create Panel to hold PictureBox and Label
Panel panel = new Panel
{
Width = pictureBoxWidth,
Height = pictureBoxHeight + 45, // Adjust height to include space for label
Margin = new Padding(5),
AutoSize = false
};
// Create PictureBox
PictureBox pictureBox = new PictureBox
{
Width = pictureBoxWidth,
Height = pictureBoxHeight,
BorderStyle = BorderStyle.None,
SizeMode = PictureBoxSizeMode.StretchImage,
Cursor = Cursors.Hand,
BackColor = Color.LightGray,
Tag = file.FullName
};
// Load thumbnail image
try
{
Bitmap rhinoThumbnail = File3dm.ReadPreviewImage(file.FullName);
if (rhinoThumbnail != null)
{
pictureBox.Image = rhinoThumbnail;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading thumbnail for {file.FullName}: {ex.Message}");
}
// Create Label
Label label = new Label
{
Text = GetMultilineTruncatedText(file.Name, pictureBoxWidth),
Dock = DockStyle.Bottom,
TextAlign = ContentAlignment.MiddleCenter,
AutoSize = false,
Width = pictureBoxWidth,
Height = 45, // Allow for two lines of text
MaximumSize = new Size(pictureBoxWidth, 45),
AutoEllipsis = true // Automatically adds ellipsis ("...") when text overflows
};
// Add PictureBox and Label to Panel
panel.Controls.Add(pictureBox);
panel.Controls.Add(label);
// Add tooltip to PictureBox for full filename
toolTip.SetToolTip(pictureBox, file.Name);
return panel;
}
// Helper function to handle multiline text with truncation
private string GetMultilineTruncatedText(string text, int maxWidth)
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
Font font = new Font("Microsoft Sans Serif", 8.25F);
StringFormat format = new StringFormat
{
Trimming = StringTrimming.EllipsisCharacter,
FormatFlags = StringFormatFlags.LineLimit
};
// Measure the complete text block with allowance for two lines
SizeF size = g.MeasureString(text, font, new SizeF(maxWidth, font.Height * 2), format);
// If it fits, return as is; otherwise, truncate to fit two lines
if (size.Height <= font.Height * 2)
{
return text;
}
// Attempt to fit text in specified width and height
Rectangle layoutRectangle = new Rectangle(Point.Empty, new Size(maxWidth, font.Height * 2));
CharacterRange[] ranges = { new CharacterRange(0, text.Length) };
format.SetMeasurableCharacterRanges(ranges);
Region[] regions = g.MeasureCharacterRanges(text, font, layoutRectangle, format);
RectangleF bounds = regions[0].GetBounds(g);
// Calculate the maximum number of characters that fit
int fittingChars = g.MeasureString(text, font, new SizeF(maxWidth, font.Height * 2), format).ToString().Length;
return text.Substring(0, fittingChars) + "...";
}
}
Key Points
AutoEllipsis: The AutoEllipsis property is automatically adding "..." when the text exceeds the specified MaximumSize. This is ideal for handling overflow text elegantly.
StringFormat and Graphics.MeasureCharacterRanges: These methods are employed for accurate measurement and truncation, especially when working with multi-line text.
Font and Size Considerations: Ensure your font settings are appropriate for your layout and design choices to ensure readability and aesthetic alignment.
This solution allows the label to display up to two lines of text, truncating with an ellipsis ("...") only if more text exists than can be displayed within the bounds you set. You can adjust margins and other settings according to your specific layout needs.
Key Adjustments
Remove ".3dm" Extension: The line text = text.Substring(0, text.Length - 4); strips the ".3dm" file extension. It makes the assumption that the extension is always exactly ".3dm" and thus removes the last four characters if it finds that the string ends with ".3dm".
Handling Edge Cases: Ensure that your string is long enough to avoid errors when modifying the substring beyond actual content. In this case, since you're targeting filenames, it should be handled correctly.
This adjustment will ensure that your labels display without the ".3dm" extension while maintaining the truncated two-line display as per your requirements.
csharp
foreach (Control control in tableLayoutPanel01.Controls)
{
if (control is IDisposable disposableControl)
{
disposableControl.Dispose();
}
}
tableLayoutPanel01.Controls.Clear();
Example: Optimize Control Usage
Instead of creating a PictureBox and Label for each item, consider rendering the contents manually using a custom-drawn list. Libraries such as OwnerDrawn list controls or more modern UI libraries might provide facilities for efficient custom rendering, reducing handle usage.
UI Virtualization
Consider implementing UI virtualization if you have a large dataset to display in your UI. UI virtualization only creates controls for currently visible items and reuses them as the user scrolls. This can significantly reduce the number of handles created.
If none of these solutions resolve your issue, you may need to use development tools to trace resource usage or even refactor how your application manages its UI to ensure efficient resource handling.
ListViewItemSorter
Other Options
Owner-Drawn Controls: You could also implement a custom control that renders the UI directly based on visible region data. It requires more work but can give you significant control over how resources are managed.
Third-Party Libraries: Consider using third-party UI libraries that offer virtualization support out of the box. Many modern libraries provide efficient virtualization options for Windows Forms.
Considerations
Handling Images: If you need to display images (thumbnails), manage these separately, perhaps using an image cache to avoid reloading images constantly.
Data Persistence: Ensure your data source can quickly provide the information needed for display without blocking the UI.
Responsive Design: Test your implementation to ensure it remains responsive as you scroll and resize the window.
By setting up a virtualized control architecture, you're effectively reducing the number of UI elements created at any one time, which can resolve the handle exhaustion problem and significantly improve performance when dealing with very large datasets.
Optimize for Display with Thumbnails:
If you're using thumbnails, manage a separate ImageList to store images and set it to the ListView.
csharp
ImageList imageList = new ImageList
{
ImageSize = new Size(100, 100), // Adjust size based on your needs
ColorDepth = ColorDepth.Depth32Bit
};
listView1.LargeImageList = imageList;
private void LoadThumbnails()
{
foreach (var file in fileCache)
{
Bitmap thumbnail = File3dm.ReadPreviewImage(file.FullName);
if (thumbnail != null)
{
imageList.Images.Add(thumbnail);
}
else
{
// Add a placeholder image if no thumbnail is available
imageList.Images.Add(Properties.Resources.PlaceholderImage);
}
}
}
Updating the File List Dynamically:
When you change directories or perform searches, update fileCache and VirtualListSize accordingly.
Search and Update Logic:
Implement logic to dynamically update fileCache and notify the ListView of the changes. This will be important when you're dynamically searching through your file data.
Considerations
Performance: This approach vastly improves performance for large sets of data by only processing data for visible items.
Selection: Handling selection and click events becomes straightforward using ListView since you can determine selected indices and process accordingly.
Scalability: This method is highly scalable and can support efficient data visualization even for very large datasets.
This example demonstrates how you can effectively use a ListView in virtual mode to handle large datasets, ensuring that only visible controls are rendered, reducing resource usage. Implementing it in your existing application will involve transitioning from your current setup to this more efficient structure.