Skip to content

Instantly share code, notes, and snippets.

@RobertBouillon
Created December 6, 2021 03:22
Show Gist options
  • Save RobertBouillon/89d8897d950c9a4e2297817cb5c8c347 to your computer and use it in GitHub Desktop.
Save RobertBouillon/89d8897d950c9a4e2297817cb5c8c347 to your computer and use it in GitHub Desktop.
Chromely Dialogs
using Chromely.Core.Network;
using System;
using System.Threading;
using USS.Tempus.Shell;
namespace TempusChromely
{
[ControllerProperty(Name = "Shell")]
public class ShellController : ChromelyController
{
public ShellController()
{
RegisterRequest("/shell/SelectFileDialog", SelectFileDialog);
RegisterRequest("/shell/SelectFolderDialog", SelectFolderDialog);
RegisterRequest("/shell/BrowsePath", BrowsePath);
}
#region Handlers
private IChromelyResponse SelectFileDialog(IChromelyRequest request) => new ChromelyResponse(request.Id) { Data = InvokeSTA(() => SelectFileDialog(request.Parameters["InitialPath"])) };
private IChromelyResponse SelectFolderDialog(IChromelyRequest request) => new ChromelyResponse(request.Id) { Data = InvokeSTA(() => SelectFolderDialog(request.Parameters["InitialPath"])) };
private IChromelyResponse BrowsePath(IChromelyRequest request)
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(request.Parameters["Path"]) { UseShellExecute = true });
return new ChromelyResponse(request.Id);
}
#endregion
#region Utilities
private DialogResponse InvokeSTA(Func<DialogResponse> func)
{
DialogResponse result = new(true, "");
var thread = new Thread(x => result = func());
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return result;
}
private DialogResponse SelectFileDialog(string initialPath)
{
var dialog = new Ookii.Dialogs.WinForms.VistaOpenFileDialog() { CheckFileExists = false };
if (initialPath is not null && System.IO.File.Exists(initialPath))
{
if (!initialPath.EndsWith('\\'))
initialPath += '\\';
dialog.InitialDirectory = initialPath;
}
var result = dialog.ShowDialog();
return new(result == System.Windows.Forms.DialogResult.Cancel, dialog.FileName);
}
private DialogResponse SelectFolderDialog(string initialPath)
{
var dialog = new Ookii.Dialogs.WinForms.VistaFolderBrowserDialog();
if (initialPath is not null && System.IO.Directory.Exists(initialPath))
{
if (!initialPath.EndsWith('\\'))
initialPath += '\\';
dialog.SelectedPath = initialPath;
}
var result = dialog.ShowDialog();
return new(result == System.Windows.Forms.DialogResult.Cancel, dialog.SelectedPath);
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment