kandi background
Explore Kits

winforms | Windows Forms is a .NET UI framework | Form library

 by   dotnet C# Version: v7.0.0-preview.3.22176.3 License: MIT

 by   dotnet C# Version: v7.0.0-preview.3.22176.3 License: MIT

Download this library from

kandi X-RAY | winforms Summary

winforms is a C# library typically used in User Interface, Form, Electron applications. winforms has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
Windows Forms is a .NET UI framework for building Windows desktop applications.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • winforms has a medium active ecosystem.
  • It has 3467 star(s) with 709 fork(s). There are 312 watchers for this library.
  • There were 10 major release(s) in the last 12 months.
  • There are 478 open issues and 1454 have been closed. On average issues are closed in 107 days. There are 41 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of winforms is v7.0.0-preview.3.22176.3
winforms Support
Best in #Form
Average in #Form
winforms Support
Best in #Form
Average in #Form

quality kandi Quality

  • winforms has 0 bugs and 0 code smells.
winforms Quality
Best in #Form
Average in #Form
winforms Quality
Best in #Form
Average in #Form

securitySecurity

  • winforms has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • winforms code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
winforms Security
Best in #Form
Average in #Form
winforms Security
Best in #Form
Average in #Form

license License

  • winforms is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
winforms License
Best in #Form
Average in #Form
winforms License
Best in #Form
Average in #Form

buildReuse

  • winforms releases are available to install and integrate.
  • It has 147 lines of code, 0 functions and 3873 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
winforms Reuse
Best in #Form
Average in #Form
winforms Reuse
Best in #Form
Average in #Form
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

winforms Key Features

Windows Forms is a .NET UI framework for building Windows desktop applications.

winforms Examples and Code Snippets

See all related Code Snippets

How To Refactor Switch Statement To Flexible Finite State Machine

copy iconCopydownload iconDownload
public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}
public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}
public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}
public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}
public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}
public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   
public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}
public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}
public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}
public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}
public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}
public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   
public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}
public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}
public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}
public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}
public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}
public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   
public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}
public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}
public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}
public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}
public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}
public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   
public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}
public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}
public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}
public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}
public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}
public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   
public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}
public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}
public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}
public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}
public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}
public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   

Embedding WebView2 DLL into wpf portable executable

copy iconCopydownload iconDownload
if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
    Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}
public static class Utils
{
    public static void CreateTempFolder()
    {
        try
        {
            string localAppData = System.IO.Path.GetTempPath()
            string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

            if (!Directory.Exists(userFilePath))
                Directory.CreateDirectory(userFilePath);
        }
        catch (Exception ex)
        {
        }
    }

    public static string GetTempFolder()
    {
        string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

        return userFilePath;
    }

    public static void DelateAllFilesInTempFolder()
    {
        try
        {
            string[] filePaths = Directory.GetFiles(GetTempFolder());
            foreach (string filePath in filePaths)
                System.IO.File.Delete(filePath);
        }
        catch (Exception ex)
        {
        }
    }
}
private void MainForm_Load(object sender, EventArgs e)
{
   Utils.CreateTempFolder();
   Utils.DelateAllFilesInTempFolder();
   ExtractWebDLLFromAssembly(Utils.GetTempFolder())
}
private void ExtractWebDLLFromAssembly(string fileLocation)
{
    string[] dllNames = new string[] { "Microsoft.Web.WebView2.Core.dll", "WebView2Loader.dll" };
    string thisAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
    foreach (string dllName in dllNames)
    {
        string dllFullPath = Path.Combine(fileLocation, dllName);
        try
        {
            File.WriteAllBytes(dllFullPath, GetAssemblyBytes(thisAssemblyName + "." + dllName));
        }
        catch
        {
            // Depending on what you want to do, continue or exit
        }
    }
}
if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
    Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}
public static class Utils
{
    public static void CreateTempFolder()
    {
        try
        {
            string localAppData = System.IO.Path.GetTempPath()
            string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

            if (!Directory.Exists(userFilePath))
                Directory.CreateDirectory(userFilePath);
        }
        catch (Exception ex)
        {
        }
    }

    public static string GetTempFolder()
    {
        string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

        return userFilePath;
    }

    public static void DelateAllFilesInTempFolder()
    {
        try
        {
            string[] filePaths = Directory.GetFiles(GetTempFolder());
            foreach (string filePath in filePaths)
                System.IO.File.Delete(filePath);
        }
        catch (Exception ex)
        {
        }
    }
}
private void MainForm_Load(object sender, EventArgs e)
{
   Utils.CreateTempFolder();
   Utils.DelateAllFilesInTempFolder();
   ExtractWebDLLFromAssembly(Utils.GetTempFolder())
}
private void ExtractWebDLLFromAssembly(string fileLocation)
{
    string[] dllNames = new string[] { "Microsoft.Web.WebView2.Core.dll", "WebView2Loader.dll" };
    string thisAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
    foreach (string dllName in dllNames)
    {
        string dllFullPath = Path.Combine(fileLocation, dllName);
        try
        {
            File.WriteAllBytes(dllFullPath, GetAssemblyBytes(thisAssemblyName + "." + dllName));
        }
        catch
        {
            // Depending on what you want to do, continue or exit
        }
    }
}
if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
    Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}
public static class Utils
{
    public static void CreateTempFolder()
    {
        try
        {
            string localAppData = System.IO.Path.GetTempPath()
            string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

            if (!Directory.Exists(userFilePath))
                Directory.CreateDirectory(userFilePath);
        }
        catch (Exception ex)
        {
        }
    }

    public static string GetTempFolder()
    {
        string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

        return userFilePath;
    }

    public static void DelateAllFilesInTempFolder()
    {
        try
        {
            string[] filePaths = Directory.GetFiles(GetTempFolder());
            foreach (string filePath in filePaths)
                System.IO.File.Delete(filePath);
        }
        catch (Exception ex)
        {
        }
    }
}
private void MainForm_Load(object sender, EventArgs e)
{
   Utils.CreateTempFolder();
   Utils.DelateAllFilesInTempFolder();
   ExtractWebDLLFromAssembly(Utils.GetTempFolder())
}
private void ExtractWebDLLFromAssembly(string fileLocation)
{
    string[] dllNames = new string[] { "Microsoft.Web.WebView2.Core.dll", "WebView2Loader.dll" };
    string thisAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
    foreach (string dllName in dllNames)
    {
        string dllFullPath = Path.Combine(fileLocation, dllName);
        try
        {
            File.WriteAllBytes(dllFullPath, GetAssemblyBytes(thisAssemblyName + "." + dllName));
        }
        catch
        {
            // Depending on what you want to do, continue or exit
        }
    }
}
if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
    Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}
public static class Utils
{
    public static void CreateTempFolder()
    {
        try
        {
            string localAppData = System.IO.Path.GetTempPath()
            string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

            if (!Directory.Exists(userFilePath))
                Directory.CreateDirectory(userFilePath);
        }
        catch (Exception ex)
        {
        }
    }

    public static string GetTempFolder()
    {
        string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        string userFilePath = Path.Combine(localAppData, "AppNameTempFiles");

        return userFilePath;
    }

    public static void DelateAllFilesInTempFolder()
    {
        try
        {
            string[] filePaths = Directory.GetFiles(GetTempFolder());
            foreach (string filePath in filePaths)
                System.IO.File.Delete(filePath);
        }
        catch (Exception ex)
        {
        }
    }
}
private void MainForm_Load(object sender, EventArgs e)
{
   Utils.CreateTempFolder();
   Utils.DelateAllFilesInTempFolder();
   ExtractWebDLLFromAssembly(Utils.GetTempFolder())
}
private void ExtractWebDLLFromAssembly(string fileLocation)
{
    string[] dllNames = new string[] { "Microsoft.Web.WebView2.Core.dll", "WebView2Loader.dll" };
    string thisAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
    foreach (string dllName in dllNames)
    {
        string dllFullPath = Path.Combine(fileLocation, dllName);
        try
        {
            File.WriteAllBytes(dllFullPath, GetAssemblyBytes(thisAssemblyName + "." + dllName));
        }
        catch
        {
            // Depending on what you want to do, continue or exit
        }
    }
}
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>

How do I reference a ListBox item

copy iconCopydownload iconDownload
$Context.Add_Click({ param($s, $e)
    if ($Null -ne $CurrentIndex) {
        $Text = $ListBox.Items[$CurrentIndex]
        # Remove clicked item
        $ListBox.Items.RemoveAt($CurrentIndex)
        # Insert uppercased string value as new item at the same index
        $ListBox.Items.Insert($CurrentIndex, $Text.ToUpper())
    }
})
using namespace System.Windows.Forms
using namespace System.ComponentModel

Add-Type -AssemblyName System.Windows.Forms

$Form = [Form]@{ StartPosition = 'CenterScreen' }
$ListBox = [ListBox]@{}

# Define the items as a strongly typed array of item strings.
[string[]] $items = @('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight')
# Wrap the array in a [BindingList[string]] instance
# and make it the listbox's data source.
$ListBox.DataSource = [BindingList[string]]::new($items)

$Form.Controls.Add($ListBox)
$ListBox.ContextMenuStrip = [ContextMenuStrip]@{}
$Context = $ListBox.ContextMenuStrip.Items.Add('ToUpper')
$ListBox.Add_MouseDown({ param($s, $e) 
    if ($e.Button -eq 'Right') { $Script:CurrentIndex = $ListBox.IndexFromPoint($e.Location) }
})
$Context.Add_Click({ param($s, $e)
    if ($null -ne $CurrentIndex) {
        # Modify the underlying array.
        $items[$CurrentIndex] = $items[$CurrentIndex].ToUpper()
        # To prevent unwanted scrolling during the refresh below, 
        # save and restore what item is currently shown at the top 
        # of the visible list portion.
        $prevTopIndex = $ListBox.TopIndex 
        # Notify the listbox via the BindingList[string] instance that
        # the items have changed.
        # !! The following *item-specific* call does NOT work.
        # !!   $ListBox.DataSource.ResetItem($CurrentIndex)
        $ListBox.DataSource.ResetBindings()
        $ListBox.TopIndex = $prevTopIndex # Restore the scrolling state.
    }
})
$Form.ShowDialog()

PowerPoint.Application.Presentations missing MsoTriState

copy iconCopydownload iconDownload
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup>
    <COMReference Include="Microsoft.Office.Core">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>8</VersionMinor>
      <VersionMajor>2</VersionMajor>
      <Guid>2df8d04c-5bfa-101b-bde5-00aa0044de52</Guid>
      <Lcid>0</Lcid>
      <Isolated>false</Isolated>
      <EmbedInteropTypes>true</EmbedInteropTypes>
    </COMReference>
    <COMReference Include="Microsoft.Office.Interop.PowerPoint">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>12</VersionMinor>
      <VersionMajor>2</VersionMajor>
      <Guid>91493440-5a91-11cf-8700-00aa0060263b</Guid>
      <Lcid>0</Lcid>
      <Isolated>false</Isolated>
      <EmbedInteropTypes>true</EmbedInteropTypes>
    </COMReference>
  </ItemGroup>

</Project>

Why does my Attach() method trigger a &quot;Entity already exists&quot; InvalidOperationException?

copy iconCopydownload iconDownload
public void AttachTest(int accountID, string link)
        {
            var accounts = Cache.GetCollection<TaxAccount>();
            var acct = accounts.FindById(accountID);
            // We set the Users relation to be null.
            acct.Users = null;

            using (var serverContext = new ApplicationDbContext(ServerOptions))
            {
                serverContext.Attach(acct);
                acct.PrivateFolderLink = link;
                serverContext.SaveChanges();
            }
        }
public void AttachTestNullUsers(int accountID, string link)
        {
            var accounts = Cache.GetCollection<TaxAccount>();
            var acct = accounts.FindById(accountID);
            // For each user, the Accounts is null, this also breaks the relationship.
            acct.Users.ForEach(X => X.Accounts = null);

            using (var serverContext ...
        }
public void AttachTest(int accountID, string link)
        {
            var accounts = Cache.GetCollection<TaxAccount>();
            var acct = accounts.FindById(accountID);
            // We set the Users relation to be null.
            acct.Users = null;

            using (var serverContext = new ApplicationDbContext(ServerOptions))
            {
                serverContext.Attach(acct);
                acct.PrivateFolderLink = link;
                serverContext.SaveChanges();
            }
        }
public void AttachTestNullUsers(int accountID, string link)
        {
            var accounts = Cache.GetCollection<TaxAccount>();
            var acct = accounts.FindById(accountID);
            // For each user, the Accounts is null, this also breaks the relationship.
            acct.Users.ForEach(X => X.Accounts = null);

            using (var serverContext ...
        }

Visual Studio 2022 view code button missing on solution explorer

copy iconCopydownload iconDownload
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>
public const string UIContextGuid = "8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B";
<GuidSymbol name="UIContextGuid" value="{8B40D5E2-5626-42AE-99EF-3DD1EFF46E7B}" />
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIXProject1Package.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideUIContextRule(VSIXProject1Package.UIContextGuid,
name: "Supported Files",
expression: "CSharp",
termNames: new[] { "CSharp" },
termValues: new[] { "HierSingleSelectionName:.cs$" })]
public sealed class VSIXProject1Package : AsyncPackage
private IServiceProvider ServiceProvider
{
    get
    {
        return this.package;
    }
}
private void Execute(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte =  ServiceProvider.GetService(typeof(DTE)) as DTE; 
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        VsShellUtilities.OpenDocumentWithSpecificEditor(package,
            item.FileNames[1],
            Microsoft.VisualStudio.VSConstants
                .VsEditorFactoryGuid.TextEditor_guid,
            Microsoft.VisualStudio.VSConstants.LOGVIEWID.Code_guid);
    }
}
private void MyQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var button = (MenuCommand)sender;
    button.Visible = false;
    var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
    ProjectItem item = dte.SelectedItems.Item(1)?.ProjectItem;
    if (item != null)
    {
        string fileExtension = 
            Path.GetExtension(item.Name).ToLowerInvariant();
        string[] supportedFiles = new[] { ".cs"};
        button.Visible = supportedFiles.Contains(fileExtension);
    }
}
<Group guid="guidVSIXProject1PackageCmdSet" 
id="SolutionToolbarGroup" priority="0xF000">
   <Parent guid="guidSHLMainMenu" id="IDM_VS_TOOL_PROJWIN"/>
</Group>
<IDSymbol name="Command1Id" value="0x0100" />
<IDSymbol name="SolutionToolbarGroup" value="0x0190"/>
<VisibilityConstraints>
   <VisibilityItem guid="guidVSIXProject1PackageCmdSet"
   id="Command1Id"
   context="UIContextGuid" />
</VisibilityConstraints>
<Button guid="guidVSIXProject1PackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
   <Parent guid="guidVSIXProject1PackageCmdSet" id="SolutionToolbarGroup" />
   <Icon guid="guidImages" id="bmpPic1" />
   <CommandFlag>DefaultInvisible</CommandFlag>
   <CommandFlag>DynamicVisibility</CommandFlag>
   <Strings>
      <ButtonText>Invoke Command1</ButtonText>
   </Strings>
</Button>

Archive folder without some subfolders and files using PowerShell

copy iconCopydownload iconDownload
$filter = {($_.Name -notlike '*.vs') -and ($_.Name -notlike '*.suo') -and ($_.Name -notlike '*.user') -and ($_.FullName -notlike '*bin\*') -and ($_.FullName -notlike '*obj\*')}
.\ArchiveOldLogs.ps1 -FileSpecs @('*.*') -Filter $filter -DeleteAfterArchiving:$false
$ParentFolder = 'C:\projects\Code\' #files will be stored with a path relative to this folder
$ZipPath = 'c:\temp\projects.zip' #the zip file should not be under $ParentFolder or an exception will be raised
$filter = {($_.Name -notlike '*.vs') -and ($_.Name -notlike '*.suo') -and ($_.Name -notlike '*.user') -and ($_.FullName -notlike '*bin\*') -and ($_.FullName -notlike '*obj\*')}
@( 'System.IO.Compression','System.IO.Compression.FileSystem') | % { [void][Reflection.Assembly]::LoadWithPartialName($_) }
Push-Location $ParentFolder #change to the parent folder so we can get $RelativePath
$FileList = (Get-ChildItem '*.*' -File -Recurse | Where-Object $Filter) #use the -File argument because empty folders can't be stored
Try{
    $WriteArchive = [IO.Compression.ZipFile]::Open( $ZipPath,'Update')
    ForEach ($File in $FileList){
        $RelativePath = (Resolve-Path -LiteralPath "$($File.FullName)" -Relative) -replace '^.\\' #trim leading .\ from path 
        Try{    
            [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($WriteArchive, $File.FullName, $RelativePath, 'Optimal').FullName
        }Catch{ #Single file failed - usually inaccessible or in use
            Write-Warning  "$($File.FullName) could not be archived. `n $($_.Exception.Message)"  
        }
    }
}Catch [Exception]{ #failure to open the zip file
    Write-Error $_.Exception
}Finally{
    $WriteArchive.Dispose() #always close the zip file so it can be read later 
}
Pop-Location
$filter = {($_.Name -notlike '*.vs') -and ($_.Name -notlike '*.suo') -and ($_.Name -notlike '*.user') -and ($_.FullName -notlike '*bin\*') -and ($_.FullName -notlike '*obj\*')}
.\ArchiveOldLogs.ps1 -FileSpecs @('*.*') -Filter $filter -DeleteAfterArchiving:$false
$ParentFolder = 'C:\projects\Code\' #files will be stored with a path relative to this folder
$ZipPath = 'c:\temp\projects.zip' #the zip file should not be under $ParentFolder or an exception will be raised
$filter = {($_.Name -notlike '*.vs') -and ($_.Name -notlike '*.suo') -and ($_.Name -notlike '*.user') -and ($_.FullName -notlike '*bin\*') -and ($_.FullName -notlike '*obj\*')}
@( 'System.IO.Compression','System.IO.Compression.FileSystem') | % { [void][Reflection.Assembly]::LoadWithPartialName($_) }
Push-Location $ParentFolder #change to the parent folder so we can get $RelativePath
$FileList = (Get-ChildItem '*.*' -File -Recurse | Where-Object $Filter) #use the -File argument because empty folders can't be stored
Try{
    $WriteArchive = [IO.Compression.ZipFile]::Open( $ZipPath,'Update')
    ForEach ($File in $FileList){
        $RelativePath = (Resolve-Path -LiteralPath "$($File.FullName)" -Relative) -replace '^.\\' #trim leading .\ from path 
        Try{    
            [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($WriteArchive, $File.FullName, $RelativePath, 'Optimal').FullName
        }Catch{ #Single file failed - usually inaccessible or in use
            Write-Warning  "$($File.FullName) could not be archived. `n $($_.Exception.Message)"  
        }
    }
}Catch [Exception]{ #failure to open the zip file
    Write-Error $_.Exception
}Finally{
    $WriteArchive.Dispose() #always close the zip file so it can be read later 
}
Pop-Location

View Serilog logs in Windows Forms application

copy iconCopydownload iconDownload
static void Main()
{
        using var watcher = new FileSystemWatcher(@"C:\path\to\folder");
        //choose what you wish
        watcher.NotifyFilter = NotifyFilters.Attributes
                             | NotifyFilters.CreationTime
                             | NotifyFilters.DirectoryName
                             | NotifyFilters.FileName
                             | NotifyFilters.LastAccess
                             | NotifyFilters.LastWrite
                             | NotifyFilters.Security
                             | NotifyFilters.Size;

        watcher.Changed += OnChanged;
        watcher.Created += OnCreated;
        watcher.Deleted += OnDeleted;
        watcher.Renamed += OnRenamed;
        watcher.Error += OnError;

        watcher.Filter = "YourLogFile.txt";
        watcher.IncludeSubdirectories = false;
        watcher.EnableRaisingEvents = true;

        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (e.ChangeType != WatcherChangeTypes.Changed)
        {
            return;
        }
        //Console.WriteLine($"Changed: {e.FullPath}");
        //Update your Listbox content
    }

Binding property in Xamarin.Forms using MVVM

copy iconCopydownload iconDownload
                            <Image RelativeLayout.WidthConstraint="{ConstraintExpression Constant=64}" 
                                   RelativeLayout.HeightConstraint="{ConstraintExpression Constant=64}" 
                                   RelativeLayout.XConstraint="{Binding X}" 
                                   RelativeLayout.YConstraint="{Binding Y}" 
                                   Source="nuclearbomb.png" />

How to call a non-static function when I cannot make the function itself static

copy iconCopydownload iconDownload
var currentMember = selfCheckout.GetCurrentMember(); //to make both check for null and call methods, you should firstly create variable with this object
if (currentMember  != null)
{
    lblMember.Text = currentMember.GetName(); // if current member is not null, call GetName
}

See all related Code Snippets

Community Discussions

Trending Discussions on winforms
  • How To Refactor Switch Statement To Flexible Finite State Machine
  • Thread is not disconnecting from server even after its file is downloaded from ftp server and not reusing itself to download another one
  • Embedding WebView2 DLL into wpf portable executable
  • How do I reference a ListBox item
  • PowerPoint.Application.Presentations missing MsoTriState
  • Why does my Attach() method trigger a &quot;Entity already exists&quot; InvalidOperationException?
  • Visual Studio 2022 view code button missing on solution explorer
  • Archive folder without some subfolders and files using PowerShell
  • Where to save .Net MAUI user settings
  • View Serilog logs in Windows Forms application
Trending Discussions on winforms

QUESTION

How To Refactor Switch Statement To Flexible Finite State Machine

Asked 2022-Mar-24 at 14:27

In a manufacturing environment, for a specific process, there are fairly straightforward C# Winforms Desktop applications that involve enum-based state machines running on infinite loop, following a structure similar to below (state names kept general for the sake of example).

switch(state):

    case STATE0:
       // code (ui update, business logic, and/or database/device communication)
       if (...)
          state = STATE1; // goes to next state

       break;

    case STATE1:
       // code (ui update, business logic, and/or database/device communication)
       if(...)
          state = STATE2; // goes to next state

       break;

    case STATE2:
       // code (ui update, business logic, and/or database/device communication)
       if(...)
          state = STATE1; // goes back to STATE1
    
       else if (...)
          state = STATE3; // goes to next state

       break;
    
    case STATE3:
       // code (ui update, business logic, and/or database/device communication)
       if (...)
          state = STATE0; // goes back to STATE0

       break;

There are many products that go through this process. There are many states across products that are almost the exact the same (e.g. state0). But product-specific logic within the states are slightly different across products.

Is there a way to refactor the above switch statement to a more cleaner, flexible finite state machine, that can account for variation within the states?

ANSWER

Answered 2022-Mar-20 at 18:52

If you have multiple states and it is necessary to change behaviour based on state, then we can use strategy pattern combined with factory pattern.

At first, we need to declare states:

public enum State
{
    State_1,
    State_2,
    State_3,
    State_4
}

Then based on state we need to choose some behaviour. We can put behaviour in class. Let's call it product. So we need to create some abstract class and put all duplicated logic in this abstract class. Then if behaviour of some classes is different or we want to add new behavior, then we will create derived classes. By adding new classes we keep to Open Closed principle.

public abstract class Product
{
    public string Name { get; set; }

    public decimal Price { get; set; }


    public string TheSameBehaviorForAllProducts() 
    {
        return "TheSameHehaviorForAllProducts";
    }


    public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "TheSameHehaviorForAllProducts";
    }
}

and derived classes of Product:

public class Product_A : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_B : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

public class Product_C : Product
{
    public override string BehaviorThatCanBeOverridenInDerivedClasses()
    {
        return "New Behavior Here";
    }
}

Then we can create a something like mapper which maps State to Product. It is also can be considered as Factory pattern:

public class StateToProduct 
{
    public Dictionary<State, Product> ProductByState = new()
        {
            { State.A, new Product_A() },
            { State.B, new Product_B() },
            { State.C, new Product_C() }
        };
}

and our state machine:

public class StateMachine
{
    // Here your logic to get state
    public State GetState() 
    {
        return State.A;
    }
}

Then we can run big system like this:

public class SomeBigSystem
{
    public void Run()
    {
        StateMachine stateMachine = new();
        StateToProduct stateToProduct = new();
        Product product = stateToProduct.ProductByState[stateMachine.GetState()];

        // executing some business logic
        product.BehaviorThatCanBeOverridenInDerivedClasses();
    }
}   

So we've created simple classes that are testable and we used here Strategy pattern.

I highly recommend you to read about SOLID and techniques of refactoring

Source https://stackoverflow.com/questions/71543432

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install winforms

You can download it from GitHub.

Support

We welcome contributions! Many people all over the world have helped make this project better.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with winforms
Consider Popular Form Libraries
Try Top Libraries by dotnet
Compare Form Libraries with Highest Support
Compare Form Libraries with Highest Quality
Compare Form Libraries with Highest Security
Compare Form Libraries with Permissive License
Compare Form Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.