Subscribe: Chris Pietschmann - Win32API
http://pietschsoft.com/syndication.axd?category=7e4b0ad3-187c-4819-9cb1-0edc104c330f
Added By: Feedage Forager Feedage Grade B rated
Language: English
Tags:
const int  const  int  menu  private  public const  public  summary public  summary  system menu  system  window  windows 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Chris Pietschmann - Win32API

Chris Pietschmann - Win32API



husband, father, hacker, entrepreneur, futurist, innovator, autodidact



 



C#: Using IProgressDialog to show a “native” Progress Dialog from .NET in Windows

Mon, 17 Aug 2009 20:03:00 -0500

A few months ago I posted some code that I originally wrote back in about 2004… Well, I was looking through some more of my prototypes that I’ve written and I came across the following example of how to use the IProgressDialog Win32 Interface to harness the power of the Built-in Progress Dialog in Windows within your own .NET applications. I have test this on WIndows 7, but it should work as expected on Windows XP and Vista. The MSDN Documentation for IProgressDialog says it’s minimum supported operating systems are Windows 2000 and Windows XP. The full source code for this example is listed below. Just copy from this post and paste it within your app to test. “ProgressDialog” Usage Example Here’s an example of how to use this example “ProgressDialog” class: This is an example of using it from Windows Forms, however it could be used from within WPF exactly the same way. using System; using System.Windows.Forms; namespace WindowsProgressDialog { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Pietschsoft.ProgressDialog pd; private uint progressPercent; private void button1_Click(object sender, EventArgs e) { pd = new Pietschsoft.ProgressDialog(this.Handle); pd.Title = "Performing Operation"; pd.CancelMessage = "Please wait while the operation is cancelled"; pd.Maximum = 100; pd.Value = 0; pd.Line1 = "Line One"; pd.Line3 = "Calculating Time Remaining..."; //pd.ShowDialog(); // Defaults to PROGDLG.Normal pd.ShowDialog(Pietschsoft.ProgressDialog.PROGDLG.Modal, Pietschsoft.ProgressDialog.PROGDLG.AutoTime, Pietschsoft.ProgressDialog.PROGDLG.NoMinimize); progressPercent = 0; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { progressPercent++; if (pd.HasUserCancelled) { timer1.Stop(); pd.CloseDialog(); } else { // Update the progress value pd.Value = progressPercent; pd.Line2 = "Percent " + progressPercent.ToString() + "%"; if (progressPercent >= 100) { timer1.Stop(); pd.CloseDialog(); } } } } }   “ProgressDialog” Class And, here’s the full code for the “ProgressDialog” class itself: using System; using System.Runtime.InteropServices; using System.Text; namespace Pietschsoft { public class ProgressDialog { private IntPtr _parentHandle; private Win32IProgressDialog pd = null; public ProgressDialog(IntPtr parentHandle) { this._parentHandle = parentHandle; } public void ShowDialog(params PROGDLG[] flags) { if (pd == null) { pd = (Win32IProgressDialog)new Win32ProgressDialog(); pd.SetTitle(this._Title); pd.SetCancelMsg(this._CancelMessage, null); pd.SetLine(1, this._Line1, false, IntPtr.Zero); pd.SetLine(2, this._Line2, false, IntPtr.Zero); pd.SetLine(3, this._Line3, false, IntPtr.Zero); PROGDLG dialogFlags = PROGDLG.Normal; if (flags.Length != 0) { dialogFlags = flags[0]; for (var i = 1; i < flags.Length; i++) { dialogFlags = dialogFlags | flags[i]; } } pd.StartProgressDialog(this._parentHandle, null, dialogFlags, IntPtr.Zero); } } public void CloseDialog() { if (pd != null) { pd.StopProg[...]



.NET Framework: Communicate through NAT Router via UPnP (Universal Plug and Play)

Thu, 05 Feb 2009 19:27:00 -0500

I've been working on an application recently that needs to be able to communicate through a router/firewall using TCP. I've read/heard a bit of information about NAT Routers and UPnP; the technoligies used in almost every router sold commercially. So, I knew that you could use the Universal Plug and Play (UPnP) features of the NAT Router to automatically open up the firewall via Port Forwarding to allow other computers on the Internet to connect directly to the one your application is running on. One thing I didn't know what that Windows (since Windows XP) has the NATUPnP 1.0 Type Library (NATUPNP.DLL) COM Component that you can utilize within your applications to do this for you. I haven't found very many articles online (via Google search) on using the NATUPnP 1.0 Type Library; there's pretty much only small code snippets available. So, I've decided to explain a little further, in this article, the What and Why of communicating through a NAT Router utilizing UPnP. What is NAT (Network Address Translation)? Network Address Translation is the method employed by a Network Router (and Wireless Routers) that allows you to have multiple computers connected to the internet using your home/work broadband internet connection. Your Router gets assigned an Internet IP Address by your Internet Service Provider, and then the Router assigns a Private IP Address to each computer on your network. The Router then "routes" Incoming and Outgoing network traffic from the Internet to the appropriate computer on your Private Network. This technique is also known as "IP masquerading", since it hides your entire Private Network from the Internet making it appear as if it were only a single computer connected to the Internet. One of the biggest side effets of NAT is that it essentially turns your Router into a Firewall. This is because when any unsolicited incoming traffic gets sent you the Router, it has no idea which computer on the Private Network might be the intended recipient. So, consiquentially, it just ignores or blocks the unsolicited incoming traffic. This is also the feature that allows you to safely enable File and Printer Sharing between the computers on the Private Network without the risk of any computer/server on the Internet being able to copy your files. Also worth noting that NAT can be implemented by other devices than a Network Router, such as: a computer running Windows with Internet Connection Sharing and Windows Firewall, or a computer running software that provides NAT. You can read more about NAT at the following links: http://en.wikipedia.org/wiki/Network_address_translation http://en.wikipedia.org/wiki/NAT_traversal What is Port Forwarding / Static NAT? Port Forwarding, also called "Static NAT", allows computers on the Internet to connect directly to a specific computer on your Private Network. This works by configuring your NAT Router to forward any incoming traffic on a specific Port to a specific computer on your network. For example you can run a Web Server by setting the NAT Router to forward all incoming traffic on Port 80 to your Web Server on your Private Network. You can read more aboug Port Forwarding at the following link: http://en.wikipedia.org/wiki/Port_forwarding What is Universal Plug and Play (UPnP)? Universal Plug and Play (UPnP) is a simple communications mechanism that allows computers and network appliances to auto-configure Port Forwarding on a NAT Router. This greatly simplifies the setup of P2P networks such that the user doesn't need to configure the NAT Router, instead the computer can connect directly to the Router and setup the appropriate Port Forwarding to allow it to accept direct connections from external computers on the Internet. This is essentially the technology that allows Peer-to-Peer Software (like Bit Torrent) to communicate through a NAT Router (Firewall) and connect directly to other computers across the Internet. There is also alot of Software and Devices that rely on this to function, such as Windows Live Messenger and XBox 360. You can read mo[...]



C#: Flash Window in Taskbar via Win32 FlashWindowEx

Mon, 26 Jan 2009 23:19:00 -0500

The Windows API (Win32) has the FlashWindowEx method within the User32 library; this method allows you (the developer) to Flash a Window, signifying to the user that some major event occurred within the application that requires their attention. The most common use of this is to flash the window until the user returns focus to the application. However, you can also flash the window a specified number of times, or just keep flashing it until you decide when to stop. The use of the FlashWindowEx method however isn't built into the .NET Framework anywhere. In order to access it you need to use the Platform Invoke (PInvoke) features of .NET to "drop" down to the Windows API (Win32) and call it directly. Also, as with many other functionalities in the Windows API (that aren't directly exposed by .NET) the FlashWindowEx method can be a little tricky to use if you aren't familiar with working with the Windows API from within .NET. Now rather than go too deep into the specifics of PInvoke or the Win32 FlashWindowEx method, below is a simple static class in C# that allows you to easily utilize this method. There is actually quite a bit of information needed to explain how to use PInvoke to utilize the Windows API (Win32), so maybe I'll cover that in a future article. Here's some example usage of this static class: // One this to note with this example usage code, is the "this" keyword is referring to // the current System.Windows.Forms.Form. // Flash window until it recieves focus FlashWindow.Flash(this); // Flash window 5 times FlashWindow.Flash(this, 5); // Start Flashing "Indefinately" FlashWindow.Start(this); // Stop the "Indefinate" Flashing FlashWindow.Stop(this); One thing to note about the FlashWindowEx method is that it requires (and will only work on) Windows 2000 or later. Here's the code for the static class in C#: public static class FlashWindow { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool FlashWindowEx(ref FLASHWINFO pwfi); [StructLayout(LayoutKind.Sequential)] private struct FLASHWINFO { /// /// The size of the structure in bytes. /// public uint cbSize; /// /// A Handle to the Window to be Flashed. The window can be either opened or minimized. /// public IntPtr hwnd; /// /// The Flash Status. /// public uint dwFlags; /// /// The number of times to Flash the window. /// public uint uCount; /// /// The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate. /// public uint dwTimeout; } /// /// Stop flashing. The system restores the window to its original stae. /// public const uint FLASHW_STOP = 0; /// /// Flash the window caption. /// public const uint FLASHW_CAPTION = 1; /// /// Flash the taskbar button. /// public const uint FLASHW_TRAY = 2; /// /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// public const uint FLASHW_ALL = 3; /// /// Flash continuously, until the FLASHW_STOP flag is set. /// public const uint FLASHW_TIMER = 4; /// /// Flash continuously until the window comes to the foreground. /// public const uint FLASHW_TIMERNOFG = 12; /// /// Flash the spacified Window (Form) until it recieves focus. /// /// The Form (Wi[...]



Add System Menu Items to WPF Window using Win32 API

Thu, 27 Mar 2008 16:41:00 -0500

A couple weeks ago, I blog how to "Add System Menu Items to a Form using Windows API". Being that WPF has it's differences from Windows Forms, I began to wonder how simple or difficult this would be to do within a WPF application. As it turns out, there are a couple of extra things you need to do, but the code is pretty much the same. This is something I used to have a code snippet for in VB6, but I haven't needed to do this in a while so I never wrote up an example in .NET. So, here's the simple code necessary to add some custom menu items to your applications System Menu within a WPF application. If you're not familiar, the System Menu is the menu that shows up if you click on the apps icon in the upper left or if you right click the app in the taskbar. Below is a screenshot of it in action along with the complete source code in C#. using System;using System.Windows;using System.Runtime.InteropServices;using System.Windows.Interop; namespace WpfApplication3{    ///     /// Interaction logic for Window1.xaml    ///     public partial class Window1 : Window    {        #region Win32 API Stuff         // Define the Win32 API methods we are going to use        [DllImport("user32.dll")]        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);         [DllImport("user32.dll")]        private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition, Int32 wFlags, Int32 wIDNewItem, string lpNewItem);         /// Define our Constants we will use        public const Int32 WM_SYSCOMMAND = 0x112;        public const Int32 MF_SEPARATOR = 0x800;        public const Int32 MF_BYPOSITION = 0x400;        public const Int32 MF_STRING = 0x0;         #endregion         // The constants we'll use to identify our custom system menu items        public const Int32 _SettingsSysMenuID = 1000;        public const Int32 _AboutSysMenuID = 1001;         ///         /// This is the Win32 Interop Handle for this Window        ///         public IntPtr Handle        {            get            {                return new WindowInteropHelper(this).Handle;            }        }         public Window1()        {            InitializeComponent();             this.Loaded += new RoutedEventHandler(Window1_Loaded);        }         private void Window1_Loaded(object sender, RoutedEventArgs e)        {            /// Get the Handle for the Forms System Menu            IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false);         [...]



Add System Menu Items to a Form using Windows API

Tue, 04 Mar 2008 19:34:00 -0500

This is something I used to have a code snippet for in VB6, but I haven't needed to do this in a while so I never wrote up an example in .NET. So, here's the simple code necessary to add some custom menu items to your applications System Menu. If you're not familiar, the System Menu is the menu that shows up if you click on the apps icon in the upper left or if you right click the app in the taskbar. Below is a screenshot of it in action along with the complete source code in C#. using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WinFormsSystemMenuTest {     public partial class Form1 : Form     {         #region Win32 API Stuff         // Define the Win32 API methods we are going to use         [DllImport("user32.dll")]         private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);         [DllImport("user32.dll")]         private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition, Int32 wFlags, Int32 wIDNewItem, string lpNewItem);         /// Define our Constants we will use         public const Int32 WM_SYSCOMMAND = 0x112;         public const Int32 MF_SEPARATOR = 0x800;         public const Int32 MF_BYPOSITION = 0x400;         public const Int32 MF_STRING = 0x0;                 #endregion                 // The constants we'll use to identify our custom system menu items         public const Int32 _SettingsSysMenuID = 1000;         public const Int32 _AboutSysMenuID = 1001;         public Form1()         {             InitializeComponent();         }         private void Form1_Load(object sender, EventArgs e)         {             /// Get the Handle for the Forms System Menu             IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false);             /// Create our new System Menu items just before the Close menu item             InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty); // <-- Add a menu seperator             InsertMenu(systemMenuHandle, 6, MF_BYPOSITION, _SettingsSysMenuID, "Settings...");             InsertMenu(systemMenuHandle, 7, MF_BYPOSITION, _AboutSysMenuID, "About...");         }         protected override void WndProc(ref Message m)         {             // Check if a System Command has been executed             if (m.Msg == WM_SYSCOMMAND)             {                 // Execute the appropriate code for the System Menu item that was clicked        [...]



VB.NET: Syntax Highlighting in a RichTextBox control

Tue, 24 May 2005 21:18:00 -0500

This last weekend I expirimented a little bit with extending the functionality of the RichTextBox control. Below you'll find an example of a small class that enherits from the RichTextBox control and allows you to implement syntax highlighting (with the use of a couple Win32 API call to smooth over the process of course.) The code pretty much speaks for itself.   Public Class SyntaxRTB    Inherits System.Windows.Forms.RichTextBox    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _       (ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer        Private Declare Function LockWindowUpdate Lib "user32" (ByVal hWnd As Integer) As Integer    Private _SyntaxHighlight_CaseSensitive As Boolean = False    Private Words As New DataTable    'Contains Windows Messages for the SendMessage API call    Private Enum EditMessages       LineIndex = 187       LineFromChar = 201       GetFirstVisibleLine = 206       CharFromPos = 215       PosFromChar = 1062    End Enum      Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)       ColorVisibleLines()    End Sub      Public Sub ColorRtb()       Dim FirstVisibleChar As Integer       Dim i As Integer = 0       While i < Me.Lines.Length          FirstVisibleChar = GetCharFromLineIndex(i)          ColorLineNumber(i, FirstVisibleChar)          i += 1       End While    End Sub      Public Sub ColorVisibleLines()       Dim FirstLine As Integer = FirstVisibleLine()       Dim LastLine As Integer = LastVisibleLine()       Dim FirstVisibleChar As Integer       If (FirstLine = 0) And (LastLine = 0) Then          'If there is no text it will error, so exit the sub          Exit Sub       Else          While FirstLine < LastLine             FirstVisibleChar = GetCharFromLineIndex(FirstLine)             ColorLineNumber(FirstLine, FirstVisibleChar)             FirstLine += 1          End While       End If    End Sub      Public Sub ColorLineNumber(ByVal LineIndex As Integer, ByVal lStart As Integer)       Dim i As Integer = 0       Dim Instance As Integer       Dim LeadingChar, TrailingChar As String       Dim SelectionAt As Integer = Me.SelectionStart       Dim MyRow As DataRow       Dim Line() As String, MyI As Integer, MyStr As String       ' Lock the update       LockWindowUpdate(Me.Handle.ToInt32)       MyI = lStart     &nb[...]