### WPF Storyboard Animation Example Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-animate-a-property-by-using-a-storyboard Initializes a WPF Page with a NameScope and sets up UI elements including a StackPanel and TextBlock for demonstrating Storyboard animations. ```VB.NET Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Media.Animation Namespace SDKSample ' Uses a storyboard to animate the properties ' of two buttons. Public Class StoryboardExample Inherits Page Private Dim WithEvents myWidthAnimatedButton As Button Private Dim WithEvents myColorAnimatedButton As Button Private Dim myWidthAnimatedButtonStoryboard As Storyboard Private Dim myColorAnimatedButtonStoryboard As Storyboard Public Sub New() ' Create a name scope for the page. NameScope.SetNameScope(Me, New NameScope()) Me.WindowTitle = "Animate Properties using Storyboards" Dim myStackPanel As New StackPanel() myStackPanel.MinWidth = 500 myStackPanel.Margin = New Thickness(30) myStackPanel.HorizontalAlignment = HorizontalAlignment.Left Dim myTextBlock As New TextBlock() myTextBlock.Text = "Storyboard Animation Example" myStackPanel.Children.Add(myTextBlock) ' ' Create and animate the first button. ' ' Create a button. myWidthAnimatedButton = New Button() myWidthAnimatedButton.Height = 30 myWidthAnimatedButton.Width = 200 myWidthAnimatedButton.HorizontalAlignment = HorizontalAlignment.Left myWidthAnimatedButton.Content = "A Button" ' Set the Name of the button so that it can be referred ' to in the storyboard that's created later. ' The ID doesn't have to match the variable name; ' it can be any unique identifier. myWidthAnimatedButton.Name = "myWidthAnimatedButton" ``` -------------------------------- ### Show the Main Window on Startup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview Open the main application window when the application starts by handling the Startup event. This example demonstrates showing a MainWindow instance. ```XAML ``` ```C# using System.Windows; namespace SDKSample { public partial class App : Application { void App_Startup(object sender, StartupEventArgs e) { // Open a window MainWindow window = new MainWindow(); window.Show(); } } } ``` ```VB.NET Imports System.Windows Namespace SDKSample Partial Public Class App Inherits Application Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) ' Open a window Dim window As New MainWindow() window.Show() End Sub End Class End Namespace ``` -------------------------------- ### Navigate to a Page on Startup for XBAP Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview For XBAP applications, navigate to a specific page when the application starts. This example uses the Startup event to initiate navigation. ```XAML ``` ```C# using System; using System.Windows; using System.Windows.Navigation; namespace SDKSample { public partial class App : Application { void App_Startup(object sender, StartupEventArgs e) { ((NavigationWindow)this.MainWindow).Navigate(new Uri("HomePage.xaml", UriKind.Relative)); } } } ``` ```VB.NET Imports System.Windows Imports System.Windows.Navigation Namespace SDKSample Partial Public Class App Inherits Application Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) CType(Me.MainWindow, NavigationWindow).Navigate(New Uri("HomePage.xaml", UriKind.Relative)) End Sub End Class End Namespace ``` -------------------------------- ### WPF Clock Control Example Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-seek-a-clock-synchronously Sets up a WPF page with a rectangle, a DoubleAnimation, and an AnimationClock to demonstrate interactive control of animations. Includes buttons for common animation control actions. ```VB.NET Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Navigation Imports System.Windows.Shapes Imports System.Data Imports System.Xml Imports System.Configuration Namespace SDKSample ''' ''' Shows how to interactively control a clock. ''' Public Class SeekAlignedToLastTickExample Inherits Page Private myClock As AnimationClock Private currentTimeIndicator As TextBlock Private seekDestination As TextBox Private rectangleWidthIndicator As TextBlock Private myRectangle As Rectangle Public Sub New() Me.WindowTitle = "Controlling a Storyboard" Me.Background = Brushes.White Dim myStackPanel As New StackPanel() myStackPanel.Margin = New Thickness(20) ' Create a rectangle. myRectangle = New Rectangle() With myRectangle .Width = 100 .Height = 20 .Margin = New Thickness(12, 0, 0, 5) .Fill = New SolidColorBrush(Color.FromArgb(170, 51, 51, 255)) .HorizontalAlignment = HorizontalAlignment.Left End With myStackPanel.Children.Add(myRectangle) ' ' Create an animation and a storyboard to animate the ' rectangle. ' Dim myDoubleAnimation As New DoubleAnimation(100, 500, New Duration(TimeSpan.FromSeconds(60))) myClock = myDoubleAnimation.CreateClock() myRectangle.ApplyAnimationClock(Rectangle.WidthProperty, myClock) myClock.Controller.Stop() ' ' Create some buttons to control the storyboard ' and a panel to contain them. ' Dim buttonPanel As New StackPanel() buttonPanel.Orientation = Orientation.Horizontal Dim beginButton As New Button() beginButton.Content = "Begin" AddHandler beginButton.Click, AddressOf beginButton_Clicked buttonPanel.Children.Add(beginButton) Dim pauseButton As New Button() pauseButton.Content = "Pause" AddHandler pauseButton.Click, AddressOf pauseButton_Clicked buttonPanel.Children.Add(pauseButton) Dim resumeButton As New Button() resumeButton.Content = "Resume" AddHandler resumeButton.Click, AddressOf resumeButton_Clicked buttonPanel.Children.Add(resumeButton) Dim skipToFillButton As New Button() skipToFillButton.Content = "Skip to Fill" AddHandler skipToFillButton.Click, AddressOf skipToFillButton_Clicked buttonPanel.Children.Add(skipToFillButton) Dim setSpeedRatioButton As New Button() setSpeedRatioButton.Content = "Triple Speed" AddHandler setSpeedRatioButton.Click, AddressOf setSpeedRatioButton_Clicked buttonPanel.Children.Add(setSpeedRatioButton) Dim stopButton As New Button() stopButton.Content = "Stop" AddHandler stopButton.Click, AddressOf stopButton_Clicked buttonPanel.Children.Add(stopButton) Dim removeButton As New Button() removeButton.Content = "Remove" AddHandler removeButton.Click, AddressOf removeButton_Clicked buttonPanel.Children.Add(removeButton) myStackPanel.Children.Add(buttonPanel) ``` -------------------------------- ### Get Local Print Queues (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/documents/printing-overview Retrieves a collection of all print queues available on the local computer. This method requires no special setup beyond having the necessary printing components installed. ```csharp /// /// Return a collection of print queues, which individually hold the features or states /// of a printer as well as common properties for all print queues. /// /// A collection of print queues. public static PrintQueueCollection GetPrintQueues() { // Create a LocalPrintServer instance, which represents // the print server for the local computer. LocalPrintServer localPrintServer = new LocalPrintServer(); // Get the default print queue on the local computer. //PrintQueue printQueue = localPrintServer.DefaultPrintQueue; // Get all print queues on the local computer. PrintQueueCollection printQueueCollection = localPrintServer.GetPrintQueues(); // Return a collection of print queues, which individually hold the features or states // of a printer as well as common properties for all print queues. return printQueueCollection; } ``` -------------------------------- ### Build and Start Generic Host in WPF App (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/how-to-use-host-builder Implement the Application_Startup event handler to create the host using CreateApplicationBuilder, register services, start the host, and display the main window. ```csharp private async void Application_Startup(object sender, StartupEventArgs e) { var builder = Host.CreateApplicationBuilder(); builder.Services.AddHostedService(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); _host = builder.Build(); await _host.StartAsync(); MainWindow mainWindow = _host.Services.GetRequiredService(); mainWindow.Show(); } ``` -------------------------------- ### Build and Start Generic Host in WPF App (VB) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/how-to-use-host-builder Implement the Application_Startup event handler in Visual Basic to create the host using CreateApplicationBuilder, register services, start the host, and display the main window. ```vb Private Async Sub Application_Startup(sender As Object, e As StartupEventArgs) Dim builder = Host.CreateApplicationBuilder() builder.Services.AddHostedService(Of SampleLifecycleService)() builder.Services.AddSingleton(Of IGreetingService, GreetingService)() builder.Services.AddSingleton(Of MainWindow)() _host = builder.Build() Await _host.StartAsync() Dim mainWindow As MainWindow = _host.Services.GetRequiredService(Of MainWindow)() mainWindow.Show() End Sub ``` -------------------------------- ### Get Local Print Queues (VB.NET) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/documents/printing-overview Retrieves a collection of all print queues available on the local computer using VB.NET. This method requires no special setup beyond having the necessary printing components installed. ```vbnet ''' ''' Return a collection of print queues, which individually hold the features or states ''' of a printer as well as common properties for all print queues. ''' ''' A collection of print queues. Public Shared Function GetPrintQueues() As PrintQueueCollection ' Create a LocalPrintServer instance, which represents ' the print server for the local computer. Dim localPrintServer As LocalPrintServer = New LocalPrintServer() ' Get the default print queue on the local computer. 'Dim printQueue As PrintQueue = localPrintServer.DefaultPrintQueue ' Get all print queues on the local computer. Dim printQueueCollection As PrintQueueCollection = localPrintServer.GetPrintQueues() ' Return a collection of print queues, which individually hold the features or states ' of a printer as well as common properties for all print queues. Return printQueueCollection End Function ``` -------------------------------- ### Initialize Designer and Get IComponentChangeService Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/creating-a-wf-control-design-time-features Override the Initialize method to get the IComponentChangeService and subscribe to its ComponentChanged event. This setup is crucial for tracking design-time changes. ```C# base.Initialize(component); IComponentChangeService cs = GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (cs != null) { cs.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); } ``` ```VB.NET MyBase.Initialize(component) Dim cs As IComponentChangeService = _ CType(GetService(GetType(IComponentChangeService)), _ IComponentChangeService) If (cs IsNot Nothing) Then AddHandler cs.ComponentChanged, AddressOf OnComponentChanged End If ``` -------------------------------- ### Setup Buttons Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-work-with-image-columns-in-the-windows-forms-datagridview-control Initializes and adds buttons to the Panel1, setting their text, size, and click event handlers. ```C# private void SetupButtons() { Button1.AutoSize = true; SetupButton(Button1, "Restart", new EventHandler(Reset)); Panel1.Controls.Add(turn); SetupButton(Button2, "Increase Cell Size", new EventHandler(MakeCellsLarger)); SetupButton(Button3, "Stretch Images", new EventHandler(Stretch)); SetupButton(Button4, "Zoom Images", new EventHandler(ZoomToImage)); SetupButton(Button5, "Normal Images", new EventHandler(NormalImage)); } ``` -------------------------------- ### Get Installed Image Decoders (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-list-installed-decoders Retrieves and displays information about all installed image decoders on the system. This code is useful for debugging or providing codec details to users. ```C# private void GetImageDecodersExample(PaintEventArgs e) { // Get an array of available decoders. ImageCodecInfo[] myCodecs; myCodecs = ImageCodecInfo.GetImageDecoders(); int numCodecs = myCodecs.GetLength(0); // Set up display variables. Color foreColor = Color.Black; Font font = new Font("Arial", 8); int i = 0; // Check to determine whether any codecs were found. if (numCodecs > 0) { // Set up an array to hold codec information. There are 9 // information elements plus 1 space for each codec, so 10 times // the number of codecs found is allocated. string[] myCodecInfo = new string[numCodecs * 10]; // Write all the codec information to the array. for (i = 0; i < numCodecs; i++) { myCodecInfo[i * 10] = "Codec Name = " + myCodecs[i].CodecName; myCodecInfo[(i * 10) + 1] = "Class ID = " + myCodecs[i].Clsid.ToString(); myCodecInfo[(i * 10) + 2] = "DLL Name = " + myCodecs[i].DllName; myCodecInfo[(i * 10) + 3] = "Filename Ext. = " + myCodecs[i].FilenameExtension; myCodecInfo[(i * 10) + 4] = "Flags = " + myCodecs[i].Flags.ToString(); myCodecInfo[(i * 10) + 5] = "Format Descrip. = " + myCodecs[i].FormatDescription; myCodecInfo[(i * 10) + 6] = "Format ID = " + myCodecs[i].FormatID.ToString(); myCodecInfo[(i * 10) + 7] = "MimeType = " + myCodecs[i].MimeType; myCodecInfo[(i * 10) + 8] = "Version = " + myCodecs[i].Version.ToString(); myCodecInfo[(i * 10) + 9] = " "; } int numMyCodecInfo = myCodecInfo.GetLength(0); // Render all of the information to the screen. int j = 20; for (i = 0; i < numMyCodecInfo; i++) { e.Graphics.DrawString(myCodecInfo[i], font, new SolidBrush(foreColor), 20, j); j += 12; } } else e.Graphics.DrawString("No Codecs Found", font, new SolidBrush(foreColor), 20, 20); } ``` -------------------------------- ### Initialize DataGridView with Columns and Styles (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-columns-in-the-windows-forms-datagridview-control Sets up a DataGridView by defining the column count, adjusting sizing, and applying a default style to the column headers. This is a foundational step before populating the grid. ```csharp private void InitializeDataGridView() { dataGridView = new System.Windows.Forms.DataGridView(); Controls.Add(dataGridView); dataGridView.Size = new Size(300, 200); // Create an unbound DataGridView by declaring a // column count. dataGridView.ColumnCount = 4; AdjustDataGridViewSizing(); // Set the column header style. DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle(); columnHeaderStyle.BackColor = Color.Aqua; columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold); dataGridView.ColumnHeadersDefaultCellStyle = columnHeaderStyle; // Set the column header names. dataGridView.Columns[0].Name = "Recipe"; dataGridView.Columns[1].Name = "Category"; dataGridView.Columns[2].Name = thirdColumnHeader; dataGridView.Columns[3].Name = "Rating"; PostColumnCreation(); } ``` -------------------------------- ### WPF Storyboard Control Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-control-a-storyboard-after-it-starts This example demonstrates how to create and control a Storyboard in WPF. It includes setup for a rectangle, animation, and buttons to control the storyboard's playback. ```vb ' ' This example shows how to control ' a storyboard after it has started. ' ' Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Shapes Imports System.Windows.Media.Animation Namespace Microsoft.Samples.Animation.TimingBehaviors Partial Public Class ControlStoryboardExample Inherits Page Private ReadOnly myStoryboard As Storyboard Public Sub New() ' Create a name scope for the page. NameScope.SetNameScope(Me, New NameScope()) WindowTitle = "Controlling a Storyboard" Background = Brushes.White Dim myStackPanel As New StackPanel With { .Margin = New Thickness(20) } ' Create a rectangle. Dim myRectangle As New Rectangle With { .Width = 100, .Height = 20, .Margin = New Thickness(12, 0, 0, 5), .Fill = New SolidColorBrush(Color.FromArgb(170, 51, 51, 255)), .HorizontalAlignment = HorizontalAlignment.Left } myStackPanel.Children.Add(myRectangle) ' Assign the rectangle a name by ' registering it with the page, so that ' it can be targeted by storyboard ' animations. RegisterName("myRectangle", myRectangle) ' ' Create an animation and a storyboard to animate the ' rectangle. ' Dim myDoubleAnimation As New DoubleAnimation(100, 500, New Duration(TimeSpan.FromSeconds(5))) Storyboard.SetTargetName(myDoubleAnimation, "myRectangle") Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty)) myStoryboard = New Storyboard() myStoryboard.Children.Add(myDoubleAnimation) ' ' Create some buttons to control the storyboard ' and a panel to contain them. ' Dim buttonPanel As New StackPanel With { .Orientation = Orientation.Horizontal } Dim beginButton As New Button With { .Content = "Begin" } AddHandler beginButton.Click, AddressOf beginButton_Clicked buttonPanel.Children.Add(beginButton) Dim pauseButton As New Button With { .Content = "Pause" } AddHandler pauseButton.Click, AddressOf pauseButton_Clicked buttonPanel.Children.Add(pauseButton) Dim resumeButton As New Button With { .Content = "Resume" } AddHandler resumeButton.Click, AddressOf resumeButton_Clicked buttonPanel.Children.Add(resumeButton) Dim skipToFillButton As New Button With { .Content = "Skip to Fill" } AddHandler skipToFillButton.Click, AddressOf skipToFillButton_Clicked buttonPanel.Children.Add(skipToFillButton) Dim setSpeedRatioButton As New Button With { .Content = "Triple Speed" } AddHandler setSpeedRatioButton.Click, AddressOf setSpeedRatioButton_Clicked buttonPanel.Children.Add(setSpeedRatioButton) Dim stopButton As New Button With { .Content = "Stop" } AddHandler stopButton.Click, AddressOf stopButton_Clicked buttonPanel.Children.Add(stopButton) myStackPanel.Children.Add(buttonPanel) Content = myStackPanel End Sub ' Begins the storyboard. Private Sub beginButton_Clicked(sender As Object, args As RoutedEventArgs) ' Specifying "true" as the second Begin parameter ' makes this storyboard controllable. myStoryboard.Begin(Me, True) End Sub ' Pauses the storyboard. Private Sub pauseButton_Clicked(sender As Object, args As RoutedEventArgs) myStoryboard.Pause(Me) End Sub ' Resumes the storyboard. Private Sub resumeButton_Clicked(sender As Object, args As RoutedEventArgs) myStoryboard.Resume(Me) End Sub ' Advances the storyboard to its fill period. Private Sub skipToFillButton_Clicked(sender As Object, args As RoutedEventArgs) myStoryboard.SkipToFill(Me) End Sub ' Updates the storyboard's speed. Private Sub setSpeedRatioButton_Clicked(sender As Object, args As RoutedEventArgs) ' Makes the storyboard progress three times as fast as normal. myStoryboard.SetSpeedRatio(Me, 3) End Sub ' Stops the storyboard. Private Sub stopButton_Clicked(sender As Object, args As RoutedEventArgs) myStoryboard.Stop(Me) End Sub End Class End Namespace ``` -------------------------------- ### Get Installed Image Decoders (VB.NET) Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-list-installed-decoders Retrieves and displays information about all installed image decoders on the system using Visual Basic.NET. This code is useful for debugging or providing codec details to users. ```VB.NET Private Sub GetImageDecodersExample(ByVal e As PaintEventArgs) ' Get an array of available decoders. Dim myCodecs() As ImageCodecInfo myCodecs = ImageCodecInfo.GetImageDecoders() Dim numCodecs As Integer = myCodecs.GetLength(0) ' Set up display variables. Dim foreColor As Color = Color.Black Dim font As New Font("Arial", 8) Dim i As Integer = 0 ' Check to determine whether any codecs were found. If numCodecs > 0 Then ' Set up an array to hold codec information. There are 9 ' information elements plus 1 space for each codec, so 10 times ' the number of codecs found is allocated. Dim myCodecInfo(numCodecs * 10) As String ' Write all the codec information to the array. For i = 0 To numCodecs - 1 myCodecInfo((i * 10)) = "Codec Name = " + myCodecs(i).CodecName myCodecInfo((i * 10 + 1)) = "Class ID = " + myCodecs(i).Clsid.ToString() myCodecInfo((i * 10 + 2)) = "DLL Name = " + myCodecs(i).DllName myCodecInfo((i * 10 + 3)) = "Filename Ext. = " + myCodecs(i).FilenameExtension myCodecInfo((i * 10 + 4)) = "Flags = " + myCodecs(i).Flags.ToString() myCodecInfo((i * 10 + 5)) = "Format Descrip. = " + myCodecs(i).FormatDescription myCodecInfo((i * 10 + 6)) = "Format ID = " + myCodecs(i).FormatID.ToString() myCodecInfo((i * 10 + 7)) = "MimeType = " + myCodecs(i).MimeType myCodecInfo((i * 10 + 8)) = "Version = " + myCodecs(i).Version.ToString() myCodecInfo((i * 10 + 9)) = " " Next i Dim numMyCodecInfo As Integer = myCodecInfo.GetLength(0) ' Render all of the information to the screen. Dim j As Integer = 20 For i = 0 To numMyCodecInfo - 1 e.Graphics.DrawString(myCodecInfo(i), _ font, New SolidBrush(foreColor), 20, j) j += 12 Next i Else e.Graphics.DrawString("No Codecs Found", _ font, New SolidBrush(foreColor), 20, 20) End If End Sub ``` -------------------------------- ### Basic Usage of PresentationHost.exe Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/wpf-host-presentationhost-exe This is the basic command to launch a WPF application using PresentationHost.exe. Replace 'example.xbap' with the actual file path or URI. ```command-line PresentationHost.exe example.xbap ``` -------------------------------- ### Get a ListBoxItem Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/listbox Shows how to retrieve a specific ListBoxItem from a ListBox. Examples are provided in XAML, C#, and Visual Basic. ```XAML ``` ```C# ListBoxItem selectedItem = (ListBoxItem)MyListBox.SelectedItem; string selectedContent = (string)selectedItem.Content; ``` ```Visual Basic Dim selectedItem As ListBoxItem = CType(MyListBox.SelectedItem, ListBoxItem) Dim selectedContent As String = CType(selectedItem.Content, String) ``` -------------------------------- ### XAML for Clock State Change Notification Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-receive-notification-when-clock-state-changes This XAML defines the UI elements and event triggers for an animation example. It sets up two rectangles, text blocks to display state information, and a button to start the animations. The Storyboard includes event handlers for CurrentStateInvalidated. ```XAML ``` -------------------------------- ### Implement Host Application to Use Add-in Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/how-to-create-an-add-in-that-is-a-ui The host application activates the add-in using the AddInStore and displays its UI. This code demonstrates rebuilding the pipeline, finding add-ins, activating one with specific security, and adding its UI to a grid. ```C# // Get add-in pipeline folder (the folder in which this application was launched from) string appPath = Environment.CurrentDirectory; // Rebuild visual add-in pipeline string[] warnings = AddInStore.Rebuild(appPath); if (warnings.Length > 0) { string msg = "Could not rebuild pipeline:"; foreach (string warning in warnings) msg += "\n" + warning; MessageBox.Show(msg); return; } // Activate add-in with Internet zone security isolation Collection addInTokens = AddInStore.FindAddIns(typeof(WPFAddInHostView), appPath); AddInToken wpfAddInToken = addInTokens[0]; this.wpfAddInHostView = wpfAddInToken.Activate(AddInSecurityLevel.Internet); // Display add-in UI this.addInUIHostGrid.Children.Add(this.wpfAddInHostView); ``` ```VB.NET ' Get add-in pipeline folder (the folder in which this application was launched from) Dim appPath As String = Environment.CurrentDirectory ' Rebuild visual add-in pipeline Dim warnings() As String = AddInStore.Rebuild(appPath) If warnings.Length > 0 Then Dim msg As String = "Could not rebuild pipeline:" For Each warning As String In warnings msg &= vbLf & warning Next warning MessageBox.Show(msg) Return End If ' Activate add-in with Internet zone security isolation Dim addInTokens As Collection(Of AddInToken) = AddInStore.FindAddIns(GetType(WPFAddInHostView), appPath) Dim wpfAddInToken As AddInToken = addInTokens(0) Me.wpfAddInHostView = wpfAddInToken.Activate(Of WPFAddInHostView)(AddInSecurityLevel.Internet) ' Display add-in UI Me.addInUIHostGrid.Children.Add(Me.wpfAddInHostView) ``` -------------------------------- ### Initialize Form and DataGridView Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/access-objects-in-a-wf-datagridviewcomboboxcell-drop-down-list Sets up the main form, including docking and sizing the DataGridView and adding a button. This code runs when the application starts. ```VB.NET Imports System.Text Imports System.Collections.Generic Imports System.Windows.Forms Public Class Form1 Inherits Form Private employees As New List(Of Employee) Private tasks As New List(Of Task) Private WithEvents reportButton As New Button Private WithEvents dataGridView1 As New DataGridView Public Sub Main() Application.Run(New Form1) End Sub Sub New() dataGridView1.Dock = DockStyle.Fill dataGridView1.AutoSizeColumnsMode = _ DataGridViewAutoSizeColumnsMode.AllCells reportButton.Text = "Generate Report" reportButton.Dock = DockStyle.Top Controls.Add(dataGridView1) Controls.Add(reportButton) Text = "DataGridViewComboBoxColumn Demo" End Sub ' Initializes the data source and populates the DataGridView control. Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As EventArgs) Handles Me.Load PopulateLists() dataGridView1.AutoGenerateColumns = False dataGridView1.DataSource = tasks AddColumns() End Sub ' Populates the employees and tasks lists. Private Sub PopulateLists() employees.Add(New Employee("Harry")) employees.Add(New Employee("Sally")) employees.Add(New Employee("Roy")) employees.Add(New Employee("Pris")) tasks.Add(New Task(1, employees(1))) tasks.Add(New Task(2)) tasks.Add(New Task(3, employees(2))) tasks.Add(New Task(4)) End Sub ' Configures columns for the DataGridView control. Private Sub AddColumns() Dim idColumn As New DataGridViewTextBoxColumn() idColumn.Name = "Task" idColumn.DataPropertyName = "Id" idColumn.ReadOnly = True Dim assignedToColumn As New DataGridViewComboBoxColumn() ' Populate the combo box drop-down list with Employee objects. For Each e As Employee In employees assignedToColumn.Items.Add(e) Next ' Add "unassigned" to the drop-down list and display it for ' empty AssignedTo values or when the user presses CTRL+0. assignedToColumn.Items.Add("unassigned") assignedToColumn.DefaultCellStyle.NullValue = "unassigned" assignedToColumn.Name = "Assigned To" assignedToColumn.DataPropertyName = "AssignedTo" assignedToColumn.AutoComplete = True assignedToColumn.DisplayMember = "Name" assignedToColumn.ValueMember = "Self" ' Add a button column. Dim buttonColumn As New DataGridViewButtonColumn() buttonColumn.HeaderText = "" buttonColumn.Name = "Status Request" buttonColumn.Text = "Request Status" buttonColumn.UseColumnTextForButtonValue = True dataGridView1.Columns.Add(idColumn) dataGridView1.Columns.Add(assignedToColumn) dataGridView1.Columns.Add(buttonColumn) End Sub ``` -------------------------------- ### Basic Form Setup with MenuStrip Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-display-option-buttons-in-a-menustrip-windows-forms Sets up the main form and initializes the MenuStrip with a main menu item. This code is typically part of the form's constructor. ```vbnet Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim mainToolStripMenuItem As New ToolStripMenuItem("Options") Dim radioButtonMenuItem1 As New ToolStripRadioButtonMenuItem("Option 1") Dim radioButtonMenuItem2 As New ToolStripRadioButtonMenuItem("Option 2") Dim radioButtonMenuItem3 As New ToolStripRadioButtonMenuItem("Option 3") mainToolStripMenuItem.DropDownItems.AddRange(New ToolStripItem() {radioButtonMenuItem1, radioButtonMenuItem2, radioButtonMenuItem3}) menuStrip1.Items.AddRange(New ToolStripItem() {mainToolStripMenuItem}) Controls.Add(menuStrip1) MainMenuStrip = menuStrip1 Text = "ToolStripRadioButtonMenuItem demo" End Sub End Class ``` -------------------------------- ### Main Entry Point for AutoSizing Application Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/automatically-resize-cells-when-content-changes-in-the-datagrid The `Main` method is the entry point for the application, starting the message loop and running the `AutoSizing` form. ```vbnet Public Shared Sub Main() Application.Run(New AutoSizing()) End Sub ``` -------------------------------- ### Form Initialization and Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-create-an-unbound-windows-forms-datagridview-control Handles the form's load event, calling methods to set up the layout, the DataGridView, and populate it with data. ```VB.NET Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load SetupLayout() SetupDataGridView() PopulateDataGridView() End Sub ``` -------------------------------- ### Configure Second GroupBox Control Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-apply-attributes-in-windows-forms-controls Sets the anchor, location, size, tab stop, and text for a GroupBox control. This example adds Start and Stop buttons to the GroupBox. ```C# this.groupBox2.Anchor = System.Windows.Forms.AnchorStyles.None; this.groupBox2.Controls.Add(this.startButton); this.groupBox2.Controls.Add(this.stopButton); this.groupBox2.Location = new System.Drawing.Point(26, 327); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(214, 68); this.groupBox2.TabIndex = 14; this.groupBox2.TabStop = false; this.groupBox2.Text = "Logging"; ``` -------------------------------- ### Program Entry Point Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls Sets up application visual styles and runs the main form. ```csharp static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } } ``` -------------------------------- ### Define Diagonal Linear Gradient Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-create-a-linear-gradient This example shows how to create a diagonal linear gradient by specifying start and end points. The gradient is then used to fill a line and an ellipse. ```C# LinearGradientBrush linGrBrush = new LinearGradientBrush(new Point(0, 0), new Point(200, 100), Color.Blue, Color.Green); Pen pen = new Pen(linGrBrush, 10); e.Graphics.DrawLine(pen, 0, 0, 200, 100); e.Graphics.FillEllipse(linGrBrush, 50, 50, 100, 100); ``` -------------------------------- ### Populate DataGridView with Sample Data Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-customize-sorting-in-the-windows-forms-datagridview-control This snippet sets up the DataGridView with columns and populates it with sample data. It's used to prepare the control for custom sorting demonstrations. ```vbnet Imports System.Windows.Forms Public Class Form1 Inherits Form Private WithEvents DataGridView1 As New DataGridView() ' Establish the main entry point for the application. Public Shared Sub Main() Application.Run(New Form1()) End Sub Public Sub New() ' Initialize the form. ' This code can be replaced with designer generated code. Me.DataGridView1.AllowUserToAddRows = False Me.DataGridView1.Dock = DockStyle.Fill Me.Controls.Add(Me.DataGridView1) Me.Text = "DataGridView.SortCompare demo" Me.PopulateDataGridView() End Sub '' ' Replace this with your own population code. Private Sub PopulateDataGridView() With Me.DataGridView1 ' Add columns to the DataGridView. .ColumnCount = 3 ' Set the properties of the DataGridView columns. .Columns(0).Name = "ID" .Columns(1).Name = "Name" .Columns(2).Name = "City" .Columns("ID").HeaderText = "ID" .Columns("Name").HeaderText = "Name" .Columns("City").HeaderText = "City" End With ' Add rows of data to the DataGridView. With Me.DataGridView1.Rows .Add(New String() {"1", "Parker", "Seattle"}) .Add(New String() {"2", "Parker", "New York"}) .Add(New String() {"3", "Watson", "Seattle"}) .Add(New String() {"4", "Jameson", "New Jersey"}) .Add(New String() {"5", "Brock", "New York"}) .Add(New String() {"6", "Conner", "Portland"}) End With ' Autosize the columns. Me.DataGridView1.AutoResizeColumns() End Sub Private Sub DataGridView1_SortCompare( ByVal sender As Object, ByVal e As DataGridViewSortCompareEventArgs) Handles DataGridView1.SortCompare ' Try to sort based on the contents of the cell in the current column. e.SortResult = System.String.Compare(e.CellValue1.ToString(), _ e.CellValue2.ToString()) ' If the cells are equal, sort based on the ID column. If (e.SortResult = 0) AndAlso Not (e.Column.Name = "ID") Then e.SortResult = System.String.Compare( DataGridView1.Rows(e.RowIndex1).Cells("ID").Value.ToString(), DataGridView1.Rows(e.RowIndex2).Cells("ID").Value.ToString()) End If e.Handled = True End Sub End Class ``` -------------------------------- ### Enumerate Local and Shared Print Queues (VB.NET) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-enumerate-a-subset-of-print-queues This VB.NET example retrieves a list of print queues that are installed locally and shared. It utilizes the EnumeratedPrintQueueTypes enumeration for filtering. ```vbnet ' Specify that the list will contain only the print queues that are installed as local and are shared Dim enumerationFlags() As EnumeratedPrintQueueTypes = {EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Shared} Dim printServer As New LocalPrintServer() 'Use the enumerationFlags to filter out unwanted print queues Dim printQueuesOnLocalServer As PrintQueueCollection = printServer.GetPrintQueues(enumerationFlags) Console.WriteLine("These are your shared, local print queues:" & vbLf & vbLf) For Each printer As PrintQueue In printQueuesOnLocalServer Console.WriteLine(vbTab & "The shared printer " & printer.Name & " is located at " & printer.Location & vbLf) Next printer Console.WriteLine("Press enter to continue.") Console.ReadLine() ``` -------------------------------- ### XAML Setup for TextWrapping Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-change-the-textwrapping-property-programmatically Defines three buttons to trigger TextWrapping changes and a TextBlock to display the wrapped text. The TextBlock's initial TextWrapping is set to 'Wrap'. ```XAML Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Lorem ipsum dolor sit aet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. ``` -------------------------------- ### Run the Application Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/how-to-implement-the-ilistsource-interface Starts the application by creating and running the main form. ```vbnet Shared Sub Main() Application.Run(New Form1()) End Sub ``` -------------------------------- ### Initialize DataGridView and Add Buttons Source: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-bands-in-the-windows-forms-datagridview-control Sets up the form, initializes buttons, and configures the DataGridView. This code is part of a larger example demonstrating band manipulation. ```C# #using #using #using #using using namespace System::Drawing; using namespace System::Windows::Forms; using namespace System; using namespace System::Collections; public ref class DataGridViewBandDemo: public Form { private: #pragma region S " form setup " public: DataGridViewBandDemo() { Button1 = gcnew Button; Button2 = gcnew Button; Button3 = gcnew Button; Button4 = gcnew Button; Button5 = gcnew Button; Button6 = gcnew Button; Button7 = gcnew Button; Button8 = gcnew Button; Button9 = gcnew Button; Button10 = gcnew Button; FlowLayoutPanel1 = gcnew FlowLayoutPanel; InitializeComponent(); thirdColumnHeader = L"Main Ingredients"; boringMeatloaf = L"ground beef"; boringMeatloafRanking = L"*"; AddButton( Button1, L"Reset", gcnew EventHandler( this, &DataGridViewBandDemo::Button1_Click ) ); AddButton( Button2, L"Change Column 3 Header", gcnew EventHandler( this, &DataGridViewBandDemo::Button2_Click ) ); AddButton( Button3, L"Change Meatloaf Recipe", gcnew EventHandler( this, &DataGridViewBandDemo::Button3_Click ) ); AddAdditionalButtons(); InitializeDataGridView(); } DataGridView^ dataGridView; Button^ Button1; Button^ Button2; Button^ Button3; Button^ Button4; Button^ Button5; Button^ Button6; Button^ Button7; Button^ Button8; Button^ Button9; Button^ Button10; FlowLayoutPanel^ FlowLayoutPanel1; private: void InitializeComponent() { FlowLayoutPanel1->Location = Point(454,0); FlowLayoutPanel1->AutoSize = true; FlowLayoutPanel1->FlowDirection = FlowDirection::TopDown; AutoSize = true; ClientSize = System::Drawing::Size( 614, 360 ); FlowLayoutPanel1->Name = L"flowlayoutpanel"; Controls->Add( this->FlowLayoutPanel1 ); Text = this->GetType()->Name; } ``` -------------------------------- ### WPF MatrixAnimationUsingPath with IsOffsetCumulative Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/animate-an-object-along-a-path-matrix-animation-with-offset Demonstrates animating a button along a path using MatrixAnimationUsingPath. Set IsOffsetCumulative to true to accumulate animation values on repeat. The animation starts on button click. ```C# using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Navigation; using System.Windows.Shapes; namespace SDKSample { /// /// Shows how to use the MatrixAnimationUsingPath.IsOffsetCumulative /// property to make a MatrixAnimatioinUsingPath accumulate /// its values when it repeats. /// public class MatrixAnimationUsingPathExampleOffsetCumulative : Page { public MatrixAnimationUsingPathExampleOffsetCumulative() { this.Margin = new Thickness(20); // Create a NameScope for the page so that // we can use Storyboards. NameScope.SetNameScope(this, new NameScope()); // Create a button. Button aButton = new Button(); aButton.MinWidth = 100; aButton.Content = "A Button"; // Create a MatrixTransform. This transform // will be used to move the button. MatrixTransform buttonMatrixTransform = new MatrixTransform(); aButton.RenderTransform = buttonMatrixTransform; // Register the transform's name with the page // so that it can be targeted by a Storyboard. this.RegisterName("ButtonMatrixTransform", buttonMatrixTransform); // Create a Canvas to contain the button // and add it to the page. // Although this example uses a Canvas, // any type of panel will work. Canvas mainPanel = new Canvas(); mainPanel.Width = 400; mainPanel.Height = 400; mainPanel.Children.Add(aButton); this.Content = mainPanel; // Create the animation path. PathGeometry animationPath = new PathGeometry(); PathFigure pFigure = new PathFigure(); pFigure.StartPoint = new Point(10, 100); PolyBezierSegment pBezierSegment = new PolyBezierSegment(); pBezierSegment.Points.Add(new Point(35, 0)); pBezierSegment.Points.Add(new Point(135, 0)); pBezierSegment.Points.Add(new Point(160, 100)); pBezierSegment.Points.Add(new Point(180, 190)); pBezierSegment.Points.Add(new Point(285, 200)); pBezierSegment.Points.Add(new Point(310, 100)); pFigure.Segments.Add(pBezierSegment); animationPath.Figures.Add(pFigure); // Freeze the PathGeometry for performance benefits. animationPath.Freeze(); // Create a MatrixAnimationUsingPath to move the // button along the path by animating // its MatrixTransform. MatrixAnimationUsingPath matrixAnimation = new MatrixAnimationUsingPath(); matrixAnimation.PathGeometry = animationPath; // Set IsOffsetCumulative to true so that the animation // values accumulate when its repeats. matrixAnimation.IsOffsetCumulative = true; matrixAnimation.Duration = TimeSpan.FromSeconds(5); matrixAnimation.RepeatBehavior = new RepeatBehavior(2); // Set the animation to target the Matrix property // of the MatrixTransform named "ButtonMatrixTransform". Storyboard.SetTargetName(matrixAnimation, "ButtonMatrixTransform"); Storyboard.SetTargetProperty(matrixAnimation, new PropertyPath(MatrixTransform.MatrixProperty)); // Create a Storyboard to contain and apply the animation. Storyboard pathAnimationStoryboard = new Storyboard(); pathAnimationStoryboard.Children.Add(matrixAnimation); // Start the animation when the button is clicked. aButton.Click += delegate(object sender, RoutedEventArgs e) { // Start the storyboard. pathAnimationStoryboard.Begin(this); }; } } } ``` -------------------------------- ### Set Binding Mode to OneTime Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/binding-declarations-overview Use the Mode property to specify the direction of the binding. This example sets the binding mode to OneTime, which updates the target property only when the application starts or when the DataContext changes. ```XAML ```