working on it ...

Filters

Explore Public Snippets

Sort by

Found 21 snippets matching: system.windows.forms

    public by p.kontalis  1228  0  6  0

    Replace Assembly.LoadWithPartialName with Assembly.Load

    The Assembly.LoadWithPartialName has been deprecated. From now on you have to use Assembly.Load
    '###Till .NET Framework 2.0 you can Load an assembly by its name
    Dim FormsAssembly As Reflection.Assembly = Reflection.Assembly.LoadWithPartialName("System.Windows.Forms")
    
    '###After .Net Framework 2.0 you have to use Assembly.Load
    '###Therefore you have to give all the assembly information but the public token is not the same per pc
    Dim FormsAssembly As Reflection.Assembly = Reflection.Assembly.Load("System.Windows.Forms, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 7a84f7ac56134e3a")
    
    '###In order to bypass this wall either you retrieve it from the registry or you use the GetType(Form) for the retrieval.
    Dim AssemblyLoadString As String = GetType(Form).AssemblyQualifiedName.ToString.Substring(GetType(Form).AssemblyQualifiedName.ToString.IndexOf(",") + 2)
    Dim FormsAssembly As Reflection.Assembly = Reflection.Assembly.Load(AssemblyLoadString)                        

    public by msdn  1396  0  6  0

    ToDataTable: Converts an IEnumerable to DataTable

    Converts an IEnumerable to DataTable IEnumerable Interface data IEnumerable container New DataTable containing data from sender using System; using System.Data; using System.Linq; using System.Windows.Forms; namespace C_Code { public partial class ExampleForm : Form { public ExampleForm() {InitializeComponent();
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;
    using System.Xml.Linq;
    
    /// <summary>
    /// Converts an IEnumerable to DataTable
    /// </summary>
    /// <typeparam name="T">IEnumerable Interface data</typeparam>
    /// <param name="sender">IEnumerable container</param>
    /// <returns>New DataTable containing data from sender</returns>
    /// <example>
    /// <code title='C# Example'>
    /// using System;
    /// using System.Data;
    /// using System.Linq;
    /// using System.Windows.Forms;
    /// namespace C_Code
    /// {
    ///     public partial class ExampleForm : Form
    ///     {
    ///         public ExampleForm()  {InitializeComponent(); }
    ///
    ///         private void button1_Click(object sender, EventArgs e)
    ///         {
    ///             /* Read comma delimited file */
    ///             var peopleData =
    ///                 from line in System.IO.File.ReadAllLines("People.txt")
    ///                 where line.Length > 0
    ///                 let Items = line.Split(',')
    ///                 select new { FirstName = Items[0], LastName = Items[1] };
    ///
    ///             /* place peopleData into a new DataTable */
    ///             DataTable peopleDataTable = peopleData.ToDataTable();
    ///         }
    ///     }
    /// }
    /// </code>
    /// <code language='vbnet' title='VB.NET Example'>
    /// Public Class ExamplesForm
    ///     Private Sub Button1_Click() Handles Button1.Click
    ///         Dim dtPeople =
    ///             (
    ///                 From line In System.IO.File.ReadAllLines("People.txt")
    ///                 Where line.Length > 0 Let Items = line.Split(","c)
    ///                 Select New With
    ///                        {
    ///                             Key .FirstName = Items(0),
    ///                             Key .LastName = Items(1)
    ///                        }
    ///             ).ToDataTable
    ///     End Sub
    /// End Class
    /// </code>
    /// </example>
    public static DataTable ToDataTable<T>(this IEnumerable<T> sender)
    {
        DataTable dt = new DataTable();
    
        // column names
        PropertyInfo[] FirstRecord = null;
    
        if (sender == null) return dt;
    
        foreach (T rec in sender)
        {
            if (FirstRecord == null)
            {
                FirstRecord = ((Type)rec.GetType()).GetProperties();
                foreach (PropertyInfo pi in FirstRecord)
                {
                    Type columnType = pi.PropertyType;
    
                    if ((columnType.IsGenericType) && (columnType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        columnType = columnType.GetGenericArguments()[0];
                    }
    
                    dt.Columns.Add(new DataColumn(pi.Name, columnType));
                }
            }
    
            DataRow dr = dt.NewRow();
    
            foreach (PropertyInfo pi in FirstRecord)
            {
                dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                (rec, null);
            }
    
            dt.Rows.Add(dr);
        }
    
        return dt;
    }

    external by flibitijibibo  3734  20  4  0

    Example to hook up an SDL2 window to a Panel for use in a System.Windows.Forms window

    Example to hook up an SDL2 window to a Panel for use in a System.Windows.Forms window: SDL2WindowExample.cs
    #region License
    /* SDL2 Window for System.Windows.Forms Example
     * Written by Ethan "flibitijibibo" Lee
     * http://www.flibitijibibo.com/
     *
     * Released under public domain.
     * No warranty implied; use at your own risk.
     */
    #endregion
    
    #region Using Statements
    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    using SDL2;
    #endregion
    
    public class SDL2WindowExample : Form
    {
    	#region Private SDL2 Window/Control Variables
    
    	// These are the variables you care about.
    	private Panel gamePanel;
    	private IntPtr gameWindow; // For FNA, this is Game.Window.Handle
    
    	#endregion
    
    	#region Private GL Variables
    
    	// IGNORE MEEEEE
    	private Random random;
    	private IntPtr glContext;
    	private delegate void Viewport(int x, int y, int width, int height);
    	private delegate void ClearColor(float r, float g, float b, float a);
    	private delegate void Clear(uint flags);
    	private Viewport glViewport;
    	private ClearColor glClearColor;
    	private Clear glClear;
    
    	#endregion
    
    	#region WinAPI Entry Points
    
    	[DllImport("user32.dll")]
    	private static extern IntPtr SetWindowPos(
    		IntPtr handle,
    		IntPtr handleAfter,
    		int x,
    		int y,
    		int cx,
    		int cy,
    		uint flags
    	);
    	[DllImport("user32.dll")]
    	private static extern IntPtr SetParent(IntPtr child, IntPtr newParent);
    	[DllImport("user32.dll")]
    	private static extern IntPtr ShowWindow(IntPtr handle, int command);
    
    	#endregion
    
    	#region Form Constructor
    
    	public SDL2WindowExample()
    	{
    		// This is what we're going to attach the SDL2 window to
    		gamePanel = new Panel();
    		gamePanel.Size = new Size(640, 480);
    		gamePanel.Location = new Point(80, 10);
    
    		// Make the WinForms window
    		Size = new Size(800, 600);
    		FormClosing += new FormClosingEventHandler(WindowClosing);
    		Button button = new Button();
    		button.Text = "Whatever";
    		button.Location = new Point(
    			(Size.Width / 2) - (button.Size.Width / 2),
    			gamePanel.Location.Y + gamePanel.Size.Height + 10
    		);
    		button.Click += new EventHandler(ClickedButton);
    		Controls.Add(button);
    		Controls.Add(gamePanel);
    
    		// IGNORE MEEEEE
    		random = new Random();
    		SDL.SDL_Init(SDL.SDL_INIT_VIDEO);
    		gameWindow = SDL.SDL_CreateWindow(
    			String.Empty,
    			0,
    			0,
    			gamePanel.Size.Width,
    			gamePanel.Size.Height,
    			SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL
    		);
    		glContext = SDL.SDL_GL_CreateContext(gameWindow);
    		glViewport = (Viewport) Marshal.GetDelegateForFunctionPointer(
    			SDL.SDL_GL_GetProcAddress("glViewport"),
    			typeof(Viewport)
    		);
    		glClearColor = (ClearColor) Marshal.GetDelegateForFunctionPointer(
    			SDL.SDL_GL_GetProcAddress("glClearColor"),
    			typeof(ClearColor)
    		);
    		glClear = (Clear) Marshal.GetDelegateForFunctionPointer(
    			SDL.SDL_GL_GetProcAddress("glClear"),
    			typeof(Clear)
    		);
    		glViewport(0, 0, gamePanel.Size.Width, gamePanel.Size.Height);
    		glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
    		glClear(0x4000);
    		SDL.SDL_GL_SwapWindow(gameWindow);
    
    		// Get the Win32 HWND from the SDL2 window
    		SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo();
    		SDL.SDL_GetWindowWMInfo(gameWindow, ref info);
    		IntPtr winHandle = info.info.win.window;
    
    		// Move the SDL2 window to 0, 0
    		SetWindowPos(
    			winHandle,
    			Handle,
    			0,
    			0,
    			0,
    			0,
    			0x0401 // NOSIZE | SHOWWINDOW
    		);
    
    		// Attach the SDL2 window to the panel
    		SetParent(winHandle, gamePanel.Handle);
    		ShowWindow(winHandle, 1); // SHOWNORMAL
    	}
    
    	#endregion
    
    	#region Button Event Method
    
    	private void ClickedButton(object sender, EventArgs e)
    	{
    		glClearColor(
    			(float) random.NextDouble(),
    			(float) random.NextDouble(),
    			(float) random.NextDouble(),
    			1.0f
    		);
    		glClear(0x4000); // GL_COLOR_BUFFER_BIT
    		SDL.SDL_GL_SwapWindow(gameWindow);
    	}
    
    	#endregion
    
    	#region Window Close Method
    
    	private void WindowClosing(object sender, FormClosingEventArgs e)
    	{
    		glClear = null;
    		glClearColor = null;
    		glViewport = null;
    		SDL.SDL_GL_DeleteContext(glContext);
    		glContext = IntPtr.Zero;
    		SDL.SDL_DestroyWindow(gameWindow);
    		gameWindow = IntPtr.Zero;
    		SDL.SDL_Quit();
    	}
    
    	#endregion
    
    	#region Program Entry Point
    
    	[STAThread]
    	static void Main()
    	{
    		Application.Run(new SDL2WindowExample());
    	}
    
    	#endregion
    }
    
    

    external by goncons  484  3  3  0

    OpenFileDialog (with multiple selection) using powershell from visual basic script. This technique could be used show any System.Windows.Forms windows or form.

    OpenFileDialog (with multiple selection) using powershell from visual basic script. This technique could be used show any System.Windows.Forms windows or form.: SelectFiles.vbs
    ' Select the file(s) on a directory
    ' Based on: http://stackoverflow.com/questions/23249895/open-file-dialog-in-vbscript-using-powershell/23251874#23251874
    '           http://stackoverflow.com/questions/216710/call-openfiledialog-from-powershell/216738#216738
    '           http://stackoverflow.com/questions/12270667/calling-powershell-with-wshshell-exec-method-hangs-the-script/13518118#13518118''
    
    ' Note: In Windows XP when a filter is selected all files/folder disapper,
    '       when a new directory (parent or other) is selected the filter begins to work normally.
    Private Function SelectFiles(InitialDir, Filter)
    	Dim result : result = ""
    
    	' Important the property ShowHelp must be $True if not the dialog is not shown
    	' See: http://stackoverflow.com/questions/216710/call-openfiledialog-from-powershell/216738#216738
    	With WScript.CreateObject("WScript.Shell").Exec( _
    		"powershell.exe -NonInteractive -NoProfile -NoLogo -Command ""& {" & _
    			"[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');" & _
    			"$objOFDialog = New-Object System.Windows.Forms.OpenFileDialog;" & _
    			"$objOFDialog.Filter = '" & Filter & "';" & _
    			"$objOFDialog.InitialDirectory = '"  & InitialDir & "';" & _
    			"$objOFDialog.Multiselect = $True;" & _
    			"$objOFDialog.RestoreDirectory = $True;" & _
    			"$objOFDialog.ShowHelp = $True;" & _
    			"$objOFDialog.SupportMultiDottedExtensions = $True;" & _
    			"$objOFDialog.Title = 'SelectFiles (" & InitialDir & ")';" & _
    			"[void]$objOFDialog.ShowDialog();" & _
    			"$objOFDialog.FileNames -join '|'" & _
    		"}""")
    		.StdIn.Close ' Important if not the script hangs:
    					 ' See: http://stackoverflow.com/questions/12270667/calling-powershell-with-wshshell-exec-method-hangs-the-script/13518118#13518118
    		While .Status = 0
    			WScript.Sleep 100
    		Wend ' .Status = 0
    		if .ExitCode = 0 Then
    			While Not .stdOut.AtEndOfStream
    				result = result & .stdOut.ReadAll
    			Wend ' Not .stdOut.AtEndOfStream
    			' Convert the string to an array of file paths
    			SelectFiles = Split(Replace(result, vbCrLf, ""), "|")
    		Else
    			While Not .stdErr.AtEndOfStream
    				result = result & .stdErr.ReadAll
    			Wend ' Not .stdErr.AtEndOfStream
    			WScript.Echo result
    			SelectFiles = False
    		End If ' .ExitCode = 0
    	End With ' WScript.CreateObject("WScript.Shell").Exec(...)
    End Function ' SelectFiles
    
    Dim SelectedFiles
    SelectedFiles = SelectFiles("C:\", "Text Files (*.txt)|*.txt|ScriptFiles (*.ps1;*.vbs)|*.ps1;*.vbs|All Files (*.*)|*.*")
    
    If IsArray(SelectedFiles) Then
    	If UBound(SelectedFiles) >= 0 Then
    		WScript.Echo "Selected Files: " & Join(SelectedFiles, vbCrLf)
    	Else
    		WScript.Echo "NO Files Selected"
    	End If ' UBound(SelectedFiles) >= 0
    	
    	WScript.Quit 0
    Else
    	WScript.Quit 1
    End If ' IsArray(SelectedFiles)
    
    

    external by Yong Wen Chua  34  0  2  0

    Calling Javascript Object Method in a System.Windows.Forms.WebBrowser Contorl

    Calling Javascript Object Method in a System.Windows.Forms.WebBrowser Contorl: WebBrowserExtensions.cs
    using System;
    using System.Linq;
    using System.Web.Script.Serialization;
    using System.Windows.Forms;
    
    namespace AsynchronousWebPage
    {
        /// <summary>
        ///     Extension convenience methods to invoke arbitrary Javascript method on a web page
        ///     hosted by a WebBrowser control.
        ///     This extensions makes use of the <see cref="System.Web.Script.Serialization.JavaScriptSerializer" />
        ///     object to serialise objects to JSON. You might need to add a reference to the
        ///     System.Web.Extensions assembly.
        /// </summary>
        public static class WebBrowserExtensions
        {
            /// <summary>
            ///     Invoke an arbitrary Javascript function on a hosted web page
            ///     Beware of the pitfall of calling this before a document has loaded: https://msdn.microsoft.com/en-us/library/cc491132.aspx
            /// </summary>
            /// <param name="browser">The WebBrowser control</param>
            /// <param name="function">The name of the Javascript function to execute. For example, "object.foobar"</param>
            /// <param name="argObjects">An array containing arguments to the function. The arguments will be serialised to JSON.</param>
            /// <returns>The result from the Javascript function, if any.</returns>
            public static Object InvokeScript(this WebBrowser browser, string function, params object[] argObjects)
            {
                var javaScriptSerializer = new JavaScriptSerializer();
                var args = String.Join(",",
                    argObjects.Select(o => javaScriptSerializer.Serialize(o)));
                const string script = "{0}({1});";
                return browser.InvokeScript(String.Format(script, function, args));
            }
    
            /// <summary>
            ///     Invoke arbitrary Javascript code on a hosted web page
            ///     Beware of the pitfall of calling this before a document has loaded: https://msdn.microsoft.com/en-us/library/cc491132.aspx
            /// </summary>
            /// <param name="browser">The WebBrowser control</param>
            /// <param name="script">Arbitrary Javascript code</param>
            /// <returns>The result from the Javascript function, if any.</returns>
            public static Object InvokeScript(this WebBrowser browser, string script)
            {
                if (browser.Document == null)
                {
                    throw new InvalidOperationException("There is no document loaded in the WebBrowser control");
                }
                // Ugly workaround: http://stackoverflow.com/questions/7322420/
                var selfExecutingScript = @"(function () { 'use strict'; function execute() { " + script +
                                          @" } return execute(); }());";
                // We can only call the InvokeScript method in the thread that owns the WebBrowser control.
                // Thus, we have to execute this via delegate using the Invoke method on the browser control.
                var action =
                    new Func<object>(() => browser.Document.InvokeScript("eval", new object[] {selfExecutingScript}));
                return browser.Invoke(action);
            }
        }
    }
    
    

    external by Syrone Wong  34  0  1  0

    Convert between System.Windows.Forms.Keys and System.Windows.Input.Key

    Convert between System.Windows.Forms.Keys and System.Windows.Input.Key: 1.cs
    Keys formsKey = Keys.A;
    Key wpfKey = Key.A;
    wpfKey = KeyInterop.KeyFromVirtualKey((int)formsKey);
    formsKey = (Keys)KeyInterop.VirtualKeyFromKey(wpfKey);
    // The KeyInterop class is the "key," plus the fact that the Windows Forms Keys enumeration has the same integer values as the Win 32 virtual key codes.
    
    

    external by ericis  11  0  2  0

    HTML Button Event Listener for System.Windows.Forms.WebBrowser

    HTML Button Event Listener for System.Windows.Forms.WebBrowser: Program.cs
    namespace ConsoleApplication1
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Windows.Forms;
    
        public class Program
        {
            private WebBrowser browser;
    
            private bool isAttached;
    
            [STAThread]
            public static int Main(string[] args)
            {
                var returnCode = 0;
    
                try
                {
                    Console.WriteLine("Running...");
                    new Program().Run();
                }
                catch (Exception ex)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: " + ex.Message);
                    returnCode = -1;
                }
    
                Console.ReadLine();
    
                return returnCode;
            }
    
            public void Run()
            {
                Form form = null;
    
                try
                {
                    form = new Form
                    {
                        Text = "Web Browser Events",
                        WindowState = FormWindowState.Maximized
                    };
    
                    var panel = new Panel
                    {
                        Dock = DockStyle.Bottom,
                        Height = 400
                    };
    
                    this.browser = new WebBrowser
                    {
                        Dock = DockStyle.Fill,
                        Url = new Uri("http://checkin.usairways.com")
                    };
    
                    panel.Controls.Add(this.browser);
    
                    form.Controls.Add(panel);
    
                    var btnAttachBrowserEvent = new Button
                    {
                        Text = "Click to attach browser event...",
                        Dock = DockStyle.Top
                    };
    
                    btnAttachBrowserEvent.Click += this.btnAttachBrowserEvent_Click;
    
                    form.Controls.Add(btnAttachBrowserEvent);
    
                    form.ShowDialog();
                }
                finally
                {
                    if (form != null && !form.IsDisposed)
                    {
                        form.Dispose();
                    }
                }
            }
    
            private void btnAttachBrowserEvent_Click(object sender, EventArgs e)
            {
                if (!this.isAttached)
                {
                    var btnInternalBrowserButton = this.browser.Document.GetElementById("LookupButton");
    
                    if (btnInternalBrowserButton == null)
                    {
                        MessageBox.Show("Couldn't find the internal browser button. Please ensure the page has fully loaded");
                        return;
                    }
    
                    btnInternalBrowserButton.Click += this.btnInternalBrowserButton_Click;
    
                    this.isAttached = true;
                }
    
                MessageBox.Show("Please click the check-in button to see this working");
            }
    
            private void btnInternalBrowserButton_Click(object sender, HtmlElementEventArgs e)
            {
                MessageBox.Show("Button inside of the browser was clicked");
            }
        }
    }
    
    

    external by kuramiya  682  0  3  0

    C# System.Windows.Forms.Timer

    C# System.Windows.Forms.Timer: Form1.cs
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Threading;
    
    namespace FormTimerLesson
    {
        public partial class Form1 : Form
        {
            private System.Windows.Forms.Timer timer;
    
            Queue<TimerTask> timerTaskQueue = new Queue<TimerTask>();
    
            public Form1()
            {
                InitializeComponent();
    
                timerTaskQueue.Enqueue(new TimerTask { WaitTime_msec = 1000, Message = "first task" });
                timerTaskQueue.Enqueue(new TimerTask { WaitTime_msec = 500, Message = "sencond task" });
                timerTaskQueue.Enqueue(new TimerTask { WaitTime_msec = 0, Message = "third task" });
    
                timer = new System.Windows.Forms.Timer();
                timer.Tick += timer_Tick;
                timer.Interval = 100;
                timer.Start();
            }
    
            void timer_Tick(object sender, EventArgs e)
            {
                if (timerTaskQueue.Count == 0)
                {
                    timer.Stop();
                    return;
                }
    
                TimerTask task = timerTaskQueue.Dequeue();
    
                Thread.Sleep(task.WaitTime_msec);
    
                textBox1.AppendText(task.Message + "\n");
            }
        }
    
        public class TimerTask
        {
            private int waitTime_msec;
    
            public int WaitTime_msec
            {
                get { return waitTime_msec; }
                set { waitTime_msec = value; }
            }
    
            private string message;
    
            public string Message
            {
                get { return message; }
                set { message = value; }
            }
        }
    }
    
    
    

    external by Matthew King  83  0  2  0

    Extension methods adding an async Show method to System.Windows.Forms.Form.

    Extension methods adding an async Show method to System.Windows.Forms.Form.: FormExtensions.cs
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    static class FormExtensions
    {
        public static Task<DialogResult> ShowAsync(this Form form)
        {
            return ShowAsync(form, null);
        }
    
        public static Task<DialogResult> ShowAsync(this Form form, IWin32Window owner)
        {
            TaskCompletionSource<DialogResult> tcs = new TaskCompletionSource<DialogResult>();
    
            FormClosingEventHandler handler = null;
            handler = new FormClosingEventHandler((s, e) =>
            {
                form.FormClosing -= handler;
                tcs.SetResult(form.DialogResult);
            });
    
            form.FormClosing += handler;
    
            form.Show(owner);
    
            return tcs.Task;
        }
    }
    
    

    external by Matthew King  60  0  2  0

    Extension methods adding an awaitable ShowAsync method to System.Windows.Forms.Form.

    Extension methods adding an awaitable ShowAsync method to System.Windows.Forms.Form.: FormExtensions.cs
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    static class FormExtensions
    {
        public static Task<DialogResult> ShowAsync(this Form form)
        {
            return ShowAsync(form, null);
        }
    
        public static Task<DialogResult> ShowAsync(this Form form, IWin32Window owner)
        {
            TaskCompletionSource<DialogResult> tcs = new TaskCompletionSource<DialogResult>();
    
            FormClosingEventHandler handler = null;
            handler = new FormClosingEventHandler((s, e) =>
            {
                form.FormClosing -= handler;
                tcs.SetResult(form.DialogResult);
            });
    
            form.FormClosing += handler;
    
            form.Show(owner);
    
            return tcs.Task;
        }
    }
    
    
    • Public Snippets
    • Channels Snippets