简体   繁体   中英

How do I use the methods of a class that comes with a C# namespace

I am a newbie to C#

So I want to use the Microsoft.Win32 namespace to show a dialog using the ShowDialog method.

Here is my code below:

using System;
using Microsoft.Win32; 


public abstract class example
{
    
    static void Main()
    {

        CommonDialog.ShowDialog();        
    }

}

I get the following error,

Class1.cs(11,9): error CS0103: The name 'CommonDialog' does not exist in the current context

Forgive my ignorance, but i simply do not know

You need to add this to the project https://www.nuget.org/packages/PresentationFramework/

  • Tools->Nuget Package Manager->Manage Nuget Packages for Solutions...
  • Click Browse
  • Search for PresentationFramework
  • Install

Furthermore, CommondDialog is an abstract class. Calling ShowDialog most likely will not work. It should not compile. I am not sure how Microsoft.Win32 namespace works but if you are new to C# and want to learn about Windows Forms, I would suggest this: https://docs.microsoft.com/en-us/visualstudio/ide/create-csharp-winform-visual-studio?view=vs-2019

@ y.

Based on my test, WPF App (.NET Framework) and WPF Application project does not need to add PresentationFramework.dll.

Add PresentationFramework.dll to the Windows Forms App and Windows Forms App (.NET Framework) project:

Right-click References (Dependencies) and select Add Reference... (Add COM Reference...)-> click Browse... ->find PresentationFramework.dll and click OK -> Confirm that PresentationFramework.dll dependency is checked and click ok.

Then you can use the following simple code to test.

using Microsoft.Win32;
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".txt"; // Default file extension
            dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                textBox1.Text = dlg.FileName;
                
            }
        }
    } 

The result is shown in the picture: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM