I found this code on SO to automatically dismiss a confirm dialog, but it is not working in Firefox.
The problem is, var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button"
&& new WinButton(w.Hwnd).Title == "OK").FirstOrDefault();
Always returns null. Is there another way to get the handle of the dialog button in firefox?
public class OKDialogHandler : BaseDialogHandler {
public override bool HandleDialog(Window window) {
var button = GetOKButton(window);
if (button != null) {
button.Click();
return true;
} else {
return false;
}
}
public override bool CanHandleDialog(Window window) {
return GetOKButton(window) != null;
}
private WinButton GetOKButton(Window window) {
var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button"
&& new WinButton(w.Hwnd).Title == "OK").FirstOrDefault();
if (windowButton == null)
return null;
else
return new WinButton(windowButton.Hwnd);
}
}
The controls on the Firefox alert() dialog are not enumerable. That is, they don't exist as separate windows like they do in IE. The best way to approach this is to create a new DialogHandler class that implements IDialogHandler. In the constructor, you can pass in the Firefox instance for which the dialog appears, and you can use the following codeto send JavaScript across to Firefox to manipulate the dialog:
FFDocument nativeDoc = firefox.NativeDocument as FFDocument;
// ClientPort has several WriteAndRead... functions,
// and takes a variable list of arguments for the script
// to be executed.
nativeDoc.ClientPort.WriteAndRead(script);
You can use the JavaScript below to click on the OK and Cancel buttons on an alert() or confirm() dialog.
private const string DialogIsConfirmScript = "typeof getWindows()[{0}].document.documentElement.getButton('accept') !== 'undefined' && typeof getWindows()[{0}].document.documentElement.getButton('cancel') !== 'undefined';";
private const string DialogIsAlertScript = "typeof getWindows()[{0}].document.documentElement.getButton('accept') !== 'undefined' && typeof getWindows()[{0}].document.documentElement.getButton('cancel') !== 'undefined' && getWindows()[{0}].document.documentElement.getButton('cancel').hidden;";
private const string ClickCancelButtonScript = "getWindows()[{0}].document.documentElement.getButton('cancel').click()";
private const string ClickOKButtonScript = "getWindows()[{0}].document.documentElement.getButton('accept').click()";
private const string WindowClassName = "MozillaDialogClass";
A more complete implementation, which wraps the native IE alert() and confirm() handling in a common interface and adds Firefox handling is available at http://pastebin.com/ZapXr9Yf
Related
Creating an app that on tap of an webview input field, has to do an action. Catching and starting the selected action works fine, but due to it being started by clicking an input field, the keyboard is requested. On Android < Version 9, my currently code works just fine to hide the keyboard, but on Android Version 9, it doesn't.
I have tried all manor or combination of what was deemed the top answer on this post, but none have worked for my app on Android 9
Below is a bit of my code from my MainActivity, where the instance of my keyboard service implementation is created. the MainActivity code is then followed by my Keyboard service implementation made for android.
[Activity(Label = "Dental.App", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ScreenOrientation = ScreenOrientation.SensorLandscape,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, WindowSoftInputMode = SoftInput.StateAlwaysHidden) ]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
...
DependencyService.Get<IServiceCollection>().SetKeyboardService(new KeyboardService(this, GetInputMethodManager()));
...
}
public InputMethodManager GetInputMethodManager()
{
return (InputMethodManager)GetSystemService(Context.InputMethodService);
}
}
public class KeyboardService : IKeyboardService
{
private InputMethodManager inputMethodManager;
private readonly object mainActivity;
public KeyboardService(object activity, InputMethodManager methodManager)
{
mainActivity = activity;
inputMethodManager = methodManager;
}
public bool IsKeyboardShown => inputMethodManager.IsAcceptingText;
public void HideKeyboard()
{
if (inputMethodManager == null || !(mainActivity is Activity activity)) return;
Logging.Log(LogType.Information, $"Attempting to Hide Keyboard via 1st method...");
//var view = activity.CurrentFocus;
var view = activity.FindViewById(Android.Resource.Id.Content).RootView;
if (view == null) Logging.Log(LogType.Warning, $"Failed to get View from Activity...");
var token = view?.WindowToken;
if (token == null) Logging.Log(LogType.Warning, $"Failed to get Token from View...");
var success = inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
Logging.Log(LogType.Information,
$"{nameof(inputMethodManager.HideSoftInputFromWindow)} returned => {success}");
if(success) view?.ClearFocus();
if (!IsKeyboardShown)
{
view?.ClearFocus();
return;
}
Logging.Log(LogType.Warning,
$"Failed to Hide Keyboard via {nameof(inputMethodManager.HideSoftInputFromWindow)}...");
HideKeyboardAttemptTwo(activity);
}
private void HideKeyboardAttemptTwo(Activity activity)
{
Logging.Log(LogType.Information, $"Attempting to Hide Keyboard via 2nd method...");
//var view = activity.CurrentFocus;
var view = activity.FindViewById(Android.Resource.Id.Content).RootView;
if (view == null) Logging.Log(LogType.Warning, $"Failed to get View from Activity...");
var token = view?.WindowToken;
if (token == null) Logging.Log(LogType.Warning, $"Failed to get Token from View...");
inputMethodManager.ToggleSoftInputFromWindow(token, ShowSoftInputFlags.None, HideSoftInputFlags.None);
if (!IsKeyboardShown)
{
view?.ClearFocus();
return;
}
Logging.Log(LogType.Warning, $"Failed to Hide Keyboard via {nameof(inputMethodManager.ToggleSoftInputFromWindow)}...");
}
public void ReInitializeInputMethod()
{
inputMethodManager = InputMethodManager.FromContext((Context) mainActivity);
}
None of the null check are coming back true, i.e nothing is null. The variable called success in the method HideKeyboard is returning false in 99% of all cases where it is called on a android version 9. In the 1% of the cases where it is true, the keyboard is still open. If the keyboard is still shown at the end of HideKeyboard, then the code attempts to close the keyboard via toggling it in the method HideKeyboardAttemptTwo. Doing it either of theses ways on Android 9 does not work, however running the exact same code on an Android 7.1 works just fine.
I'm not entirely sure that i have implemented the use of ToggleSoftInputFromWindow correctly, it is intended to only be able to run when the keyboard is open, i.e always used to hide the keyboard.
To reiterate my question: How do it successfully hide the keyboard on an Android 9.
If any additional information is needed, just ask, and i will attempt to find and supply it.
I uses this for my app, give it a try
Interface in main project
namespace *.Services.Interfaces
{
public interface IForceKeyboardDismissalService
{
void DismissKeyboard();
}
}
Phone specific code
using Plugin.CurrentActivity; //Nugget used to get activity
[assembly: Xamarin.Forms.Dependency(typeof(AndroidForceKeyboardDismissalService))]
namespace *.Droid.PhoneSpecific
{
public class AndroidForceKeyboardDismissalService : IForceKeyboardDismissalService
{
public void DismissKeyboard()
{
var imm = InputMethodManager.FromContext(CrossCurrentActivity.Current.Activity.ApplicationContext);
imm?.HideSoftInputFromWindow(CrossCurrentActivity.Current.Activity.Window.DecorView.WindowToken, HideSoftInputFlags.NotAlways);
var currentFocus = CrossCurrentActivity.Current.Activity.CurrentFocus;
if (currentFocus != null && currentFocus is EditText)
currentFocus.ClearFocus();
}
}
}
Usage
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
Let me know if its working for you.
To fix my problem i injected some JavaScript into the Webview, wherein i unfocused the input field, that was clicked.
On my Webview class i created a method that, given the string id of an element, would toggle whether or not that element is focused. As a second input, a boolean can be supplied, but defaulted to True, to indicate whether or not, you only want to unfocus the element.
public class AdvancedWebView : HybridWebView
{
...
public void ToggleElementFocus(string elementId, bool onlyUnFocus = true)
{
var js = GetJsInvertFocus(elementId, onlyUnFocus);
InjectJavaScript(js);
// Logging.Logging.Log(LogType.Information, $"Injected Javascript => {js}");
}
...
private string GetJsInvertFocus(string elementId, bool onlyUnFocus)
{
var builder = new StringBuilder();
builder.Append($"if (document.getElementById('{elementId}'))");
builder.Append("{");
builder.Append($"var element = document.getElementById('{elementId}');");
builder.Append($"if (element === document.activeElement)");
builder.Append("{");
builder.Append($"element.blur();");
builder.Append("}");
builder.Append($"else if({onlyUnFocus} == False)");
builder.Append("{");
builder.Append($"element.focus();");
builder.Append("}");
builder.Append("}");
return builder.ToString();
}
...
}
I'm extending the HybridWebview from XLabs, as it already has the functionality to inject JavaScript into the Webview. So that is where i get the InjectJavaScript method from.
On my page in my app, with the Webview, i then have a method that runs, when the element is clicked. To get a click event when clicking the Webview look at this link. During the method i figure out what the element id is from the event arguments, and then use this id to inject the JavaScript shown above, to unfocus the element, causing the keyboard to not appear at all. Below my OnClicked method can be seen.
public partial class DentalWebPage : AdvancedTabbedPage
{
...
private void DentalWebView_OnClicked(object sender, ClickEvent e)
{
try
{
if (LogUserPosition(sender, e)) return;
SwapToScanningTap();
}
catch (Exception ex)
{
Logging.Log(LogType.Exception,
ex.GetType().Namespace == typeof(BaseException).Namespace
? $"{ex.GetType()} => {ex}"
: $"{ex.GetType()} => {ex.Message}; Stacktrace => {ex.StackTrace}");
}
}
private bool LogUserPosition(object sender, ClickEvent e)
{
if (Config.DebugMode) Logging.Log(LogType.Debug, $"WebView was clicked...");
if (Config.DebugMode) Logging.Log(LogType.Debug, $"Element that was clicked is the following one => {e.Element}");
var success = Enum.TryParse(e.Element.Split(' ')[1].Split('=')[1], out clickedInputId);
if (!success && !(clickedInputId == InputId.MainContent_TextBoxInputStr ||
clickedInputId == InputId.MainContent_TextBoxScanOrder ||
clickedInputId == InputId.MainContent_TextBoxSelectProd ||
clickedInputId == InputId.MainContent_TextBoxStockReturn))
return true;
if (Config.DebugMode && webPageEnding == WebsiteControllers.Stock.ToString().ToLowerInvariant())
Logging.Log(LogType.Debug, $"WebView was clicked while on the stock page...");
return false;
}
private void SwapToScanningTap()
{
PerformOnMainThread(() =>
{
CurrentPage = Children[1];
ScanningToggle.IsToggled = true;
try
{
var isKeyboardShown = services.KeyboardService.IsKeyboardShown;
if (Config.DebugMode) Logging.Log(LogType.Debug, $"IsKeyboardShown returns => {isKeyboardShown}");
DentalWebView.ToggleElementFocus(clickedInputId.ToString());
}
catch (ObjectDisposedException)
{
if (DisposedReattempt) throw;
if (Config.DebugMode)
Logging.Log(LogType.Debug,
$"Input Method has been Disposed; Attempting to reinitialize it and rerun the {nameof(SwapToScanningTap)} method ones again");
DisposedReattempt = true;
services.KeyboardService.ReInitializeInputMethod();
SwapToScanningTap();
}
});
}
...
private void PerformOnMainThread(Action action)
{
try
{
Device.BeginInvokeOnMainThread(action);
}
catch (Exception ex)
{
Logging.Log(LogType.Exception,
ex.GetType().Namespace == typeof(BaseException).Namespace
? $"{ex.GetType()} => {ex}"
: $"{ex.GetType()} => {ex.Message}; Stacktrace => {ex.StackTrace}");
}
}
}
If you wish to get a understanding of the format of the string contained in e.Element, then go and look at the link supplied earlier.
Fell free to ask further questions, in case i missed something.
Can anyone help me understand why my call to dialogservice executes after the CanNavigateAway function has returned its value? (My goal is to warn the user they are about to navigate away from a view without saving their changes. If they click OK, the navigation is allowed. I'm using MVVM Light.
When I step through the code, it does reach the dialog service, but then proceeds to the end of CanNavigateAway before creating the dialog. The CanNavigateAway method is called by OnNavigatingFrom.
public bool CanNavigateAway()
{
if (!changesSaved && Model.IsModified && !continueNavigation)
{
dialogService.ShowMessage("Are you sure you want to continue?",
"Confirmation",
buttonConfirmText: "Continue", buttonCancelText: "Discard",
afterHideCallback: (confirmed) =>
{
if (confirmed)
{
// User has pressed the "confirm" button.
// ...
continueNavigation = true;
}
else
{
// User has pressed the "cancel" button
// (or has discared the dialog box).
// ...
continueNavigation = false;
}
});
return continueNavigation;
}
}
Here is the OnNavigatingFrom method from the MVVM Light Bindable Page class:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
if (!navigableViewModel.CanNavigateAway())
{
e.Cancel = true;
}
}
}
I tried this a different way to get the dialog service out of the mix, but showConfirmationDialogAsync still does not seem to execute in time:
public bool CanNavigateAway()
{
continueNavigation = false;
if (!changesSaved && Model.IsModified && !continueNavigation)
{
showConfirmationDialogAsync();
return continueNavigation;
}
private async void showConfirmationDialogAsync()
{
continueNavigation = false;
ContentDialog noSaveConfirmation = new ContentDialog
{
Title = "Warning",
Content = "You have unsaved changes. Are you sure you want to leave this page without saving?",
PrimaryButtonText = "Leave without saving",
SecondaryButtonText = "Stay and finish"
};
ContentDialogResult result = await noSaveConfirmation.ShowAsync();
if (result == ContentDialogResult.Primary)
{
continueNavigation = true;
}
else if (result == ContentDialogResult.Secondary)
{
continueNavigation = false;
}
}
None of the solutions will work if you require a response from the user. The problem is that when the code is inside the navigation event handler, it is running on the UI thread and the user prompt runs asynchronously, so that the UI is free to present the dialog to the user. This however means that the event handler finishes before the user has a chance to respond.
However, you can use a workaround solution. Add a flag bool field like forceNavigation. Then inside the OnNavigatingFrom display the dialog to the user and set Cancel to true right away and display the user the confirmation dialog. If the user says yes, then set forceNavigaiton to true and trigger the navigation manually again. Now it will skip the confirmation part and navigate right away.
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
//if navigation is forced, skip all logic
if ( !forceNavigation )
{
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
e.Cancel = true;
//display the dialog to the user, if he says yes, set
//forceNavigation = true; and repeat the navigation (e.g. GoBack, ... )
}
}
}
I would like to add additional menu items to my context menu. Ideally the items are enabled using validateMenuItem:
[Action("validateMenuItem:")]
public bool ValidateMenuItem(NSMenuItem item)
{
_logger.DebugFormat("Validating {0} menu item with Action {1}", item.Title, item.Action.Name);
var target = item.Target;
var menuItem = ViewModel.ContextMenu.Where(x => x.Title == item.Title).FirstOrDefault();
if (menuItem != null) {
return menuItem.Command.CanExecute();
}
return false;
}
per https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MenuList/Articles/EnablingMenuItems.html. If I manually create an action this gets called, but if I assign an eventhandler like so:
var nsMenuItem = new NSMenuItem(menuItem.Title,
(sender, e) =>
{
menuItem.Command.ExecuteAsync();
});
nsMenuItem.Target = this;
validateMenuItem: does not get called. The Action that is assigned using this method is __monomac_internal_ActionDispatcher_activated: from https://github.com/xamarin/xamarin-macios/blob/master/src/AppKit/ActionDispatcher.cs (help me please Rolf Bjarne Kvinge). Since I do not have this action in my class (I think), validateMenuItem is never called and my menu item is never activated. How can I make this work?
Update. If I add this to my view controller,
[Action("__monomac_internal_ActionDispatcher_activated:")]
public void MonomacInternalAction(NSObject sender)
{
}
validateMenuItem: gets called for the new items. However, the event handler is replaced by this function. (This problem might not be solvable!) This might be an Export vs Action issue - I see
const string skey = "__monomac_internal_ActionDispatcher_activated:";
[Preserve, Export (skey)]
public void OnActivated (NSObject sender)
{
EventHandler handler = Activated;
if (handler != null)
handler (sender, EventArgs.Empty);
}
Update 2. just found https://bugzilla.xamarin.com/show_bug.cgi?id=51343
Update 3. I can cheat the validateMenuItem by using
public override bool RespondsToSelector(ObjCRuntime.Selector sel)
{
if (sel.Name.Contains("__monomac_internal_ActionDispatcher_activated")) {
return true;
}
return base.RespondsToSelector(sel);
}
now if I could only find a way of calling the original event!
This issue is a bug in the Xamarin.Mac implementation - https://bugzilla.xamarin.com/show_bug.cgi?id=51343. I ended up with a workaround. Instead of using an eventhandler or a separate action for each menu item (couldn't figure out how to register), I created a single action to handle all menu items.
[Action("contextAction:")]
public void contextAction(NSObject sender)
{
if (sender is NSMenuItem)
{
var nsMenuItem = (NSMenuItem)sender;
var wrapper = nsMenuItem.RepresentedObject as NSObjectWrapper;
if (wrapper != null) {
var menuItem = wrapper.Context as MenuItem;
if (menuItem != null) {
menuItem.Command.ExecuteAsync();
}
}
}
}
then
foreach (var menuItem in ViewModel.ContextMenu)
{
var selector = new ObjCRuntime.Selector("contextAction:");
var nsMenuItem = new NSMenuItem(menuItem.Title, selector, "");
nsMenuItem.RepresentedObject = new NSObjectWrapper(menuItem);
NSObjectWrapper comes from Monotouch: convert an Object to NSObject.
I am trying to run a block of code when my WPF window is not open. Following code is not working please check it and let me know where I am doing wrong.
var window = IsWindowOpen<Window>(this.Title);
if(window)
{
//do something
}
else
{
// My code block
}
public static bool IsWindowOpen<T>(string name = null) where T : Window
{
var windows = Application.Current.Windows.OfType<T>();
return string.IsNullOrEmpty(name) ?
Application.Current.Windows.OfType<T>().Any() :
Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
}
You are passing Window.Title, but then in your IsWindowOpen function you are trying to match Window.Name
Okay, so please don't flame me too much, this is my 1st question here, and maybe what I am trying to do is not even possible. Obviously I am not an expert; that's why I am coming to you. :)
I have searched all over here, MSDN, and the rest of the internet (most of which points back here) without any luck. I did see one question asking about using the OpenFileDialog to select a folder instead of a file. I am almost certain that I have seen this in mainstream applications, but the question was marked as being too vague, and that particular caveat was unaddressed in the responses.
I have some text boxes that need file/folder paths. I want to simplify the two methods that handle this, into one. The only difference, is that once selects a file, and the other selects a folder. For simplicity and readability, I'd like to consolidate them.
Is this possible, without literally putting the contents of each code method into a big IF ?
Here are the two methods:
private void FolderBrowser(object sender, EventArgs e)
{
TextBox SenderBox = sender as TextBox;
if (SenderBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
FileBrowserDialog.FileName = SenderBox.Text;
}
if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
{
SenderBox.Text = FileBrowserDialog.FileName;
}
}
private void FileBrowser(object sender, EventArgs e)
{ //basically the same as the folder browser above, but for selecting specific files
TextBox SenderBox = sender as TextBox;
if (SenderBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
FileBrowserDialog.FileName = SenderBox.Text;
}
if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
{
SenderBox.Text = FileBrowserDialog.FileName;
}
}
I have added a Tag to each TextBox, indicating if it needs a file or a folder. I'd like to use the Tag as the condition by which I determine if I should be using a file or folder browser. This is where my ignorance shows; I had envisioned something like this NONWORKING code:
private void browser(object sender, EventArgs e)
{
//cast sender as a textbox
TextBox tBox = (TextBox)sender;
object browser = null;
if (tBox.Tag.ToString().Equals("Folder"))
{
browser = new FolderBrowserDialog();
}
else
{
browser = new OpenFileDialog();
}
if (tBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
browser.FileName = tBox.Text;
}
if (browser.ShowDialog() == DialogResult.OK)
{
tBox.Text = browser.FileName;
}
}
Am I crazy, or is there a way to accomplish what I have in mind? To be clear, I want to know if there is:
An existing Object/Method that would allow for the selection of a file or a folder, or
A way to dynamically re-define an object as a different type of object
Any other way to use 1 Method to dynamically allow for the use of OpenFileDialog or FileBrowserDialog based on some Tag defined on the calling object.
This is the easiest way I've found of solving this problem without relying on third party code, but you'll need to add some sanity checks, in case the user goofs around with the input:
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = false;
string defaultFilename = "Select this folder";
ofd.FileName = defaultFilename;
if (ofd.ShowDialog().Value)
{
// Check if the user picked a file or a directory, for example:
if (!ofd.FileName.Contains(defaultFilename))
{
// File code
}
else // You should probably turn this into an else if instead
{
// Directory code
}
// Alternatively, but still as unsafe
if (File.Exists(ofd.FileName))
{
// File code
}
else
{
// Directory code
}
}
Basically, the "trick" here is to set OpenFileDialog's CheckFileExists to false.
Try using FolderBrowserDialogEx.
See detailed answers here:
How do you configure an OpenFileDialog to select folders?
Both dialogs (FileOpenDialog and FolderBrowserDialog) inherit from CommonDialog; however, this base class has no property to retrieve the result. Moreover, the property is named differently in both dialogs.
You can solve the problem by creating a wrapper. Inheritance is the proper way of re-defining an object as different type.
public abstract class FileFolderDialogBase
{
public abstract bool ShowDialog();
public string Result { get; protected set; }
}
public class FileDialog : FileFolderDialogBase
{
public override bool ShowDialog()
{
var ofd = new OpenFileDialog();
if ofd.ShowDialog() == DialogResult.OK) {
Result = ofd.FileName;
return true;
}
return false;
}
}
public class FolderDialog : FileFolderDialogBase
{
public override bool ShowDialog()
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
Result = fbd.SelectedPath;
return true;
}
return false;
}
}
Usage:
var dialog = textBox.Tag == "Folder" ? new FolderDialog() : new FileDialog;
if (dialog.ShowDialog()) {
textBox.Text = dialog.Result;
}
You can push it further by creating a factory class
public static class FileFolderDialog
{
public static FileFolderDialogBase Create(string type)
{
swich (type.ToLowerInvariant()) {
case "folder":
case "dir":
case "directory":
return new FolderDialog();
default:
return new FileDialog();
}
}
}
Usage
var dialog = FileFolderDialog.Create(textBox.Tag);
if (dialog.ShowDialog()) {
textBox.Text = dialog.Result;
}
why you not try extending the TextBox Class?
It's easy and reusable and you only need to drag and drop your custom control to the WinForm
class FileTextBox : System.Windows.Form.TextBox{
//===>This enumeration is more readable insted of a string XD
public enum DialogType{
File,Folder
}
//===>This property we will handle what kind of Dialog to show
public DialogType OpenDialogType{
get;
set;
}
//===>This is where Object Oriented Programming a& Design do his magic
public System.Windows.Forms.DialogResult ShowDialog(string Title =""){
//===>This function is where we define what kind of dialog to show
System.Windows.Forms.DialogResult Result = System.Windows.Forms.DialogResult.None ;
object Browser=null;
switch(this.OpenDialogType){
case DialogType.File:
Browser = new OpenFileDialog();
((Browser)OpenFileDialog).Title= Title;
if(this.Text.Trim() !="" && this.Text != null ){
((Browser)OpenFileDialog).FileName = this.Tex;
}
Result = ((Browser)OpenFileDialog).ShowDialog();
break;
case DialogType.Folder:
Browser = new FolderBrowserDialog ();
((Browser)FolderBrowserDialog).Description = Title;
if(this.Text.Trim() !="" && this.Text != null ){
((Browser)FolderBrowserDialog).RootFolder = this.Text;
}
Result = ((Browser)FolderBrowserDialog).ShowDialog();
break;
}
return Result;//===>We return thi dialog result just if we want to do something else
}
}
/*
Create a class and copy/paste this code, I think is going to work because
I didn't compiled then go to ToolBox window find this control and Drag & Drop
to your WinForm and in the property window find OpenDialogType property
and this is where you kind define the behavior of OpenDialog();
I'm currently working in a little project in Vs where I create a custom
UI Control downloaded from my git repository
https://github.com/MrAlex6204/GYMSystem
*/