Solved

C# WPF URL/TItle from Firefox Swedish letters

Posted on 2013-01-13
7
791 Views
Last Modified: 2013-01-24
I am using this code to get current URL from Firefox

            DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
            dde.Connect();
            string url = dde.Request("URL", int.MaxValue);
            dde.Disconnect();

Open in new window


It woks greate, but when entering Swedish website I get problems

Example:
Accessing http://www.binero.se/
The WPF acplication gives me
http://www.binero.se/,Sveriges v?nligaste webbhotell - Binero,

Its supose to be
http://www.binero.se/,Sveriges vänligaste webbhotell - Binero,

How can I solve this so the URL and title can show swedish letters, Å Ä Ö :)
Thanks

Btw if you are going to try this code I recommend installing NDde
http://ndde.codeplex.com/
0
Comment
Question by:chugarah
  • 4
  • 3
7 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38775798
That is an issue with Unicode encoding, and I don't see how you can get around that issue with the DdeClient.  Where are you getting the implementation for DdeClient?
0
 
LVL 1

Author Comment

by:chugarah
ID: 38780673
Yes, I think the same. its wery strange.. Will post the whole code most be something I have done somewhere..?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.IO;
using System.ComponentModel;
using System.Threading;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Diagnostics;
using SharpPcap;
using SharpPcap.LibPcap;
using PacketDotNet;
using System.Net.Sockets;
using System.Net;
using NDde.Client;
using System.Text.RegularExpressions;
using WindowsInput;
using System.Net.NetworkInformation;




namespace BrowSerSniffer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summar1y>
    /// 


    public partial class MainWindow : Window
    {

        const int WM_GETTEXT = 0xD;
        public string name;
        public string rawUrl;
        public string urlTitle;
        public string fileStatus;
        public string hostFileActive;


        // Deklarerar bakgrundsabetare
        private readonly BackgroundWorker insaneWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = false };
        private readonly BackgroundWorker insaneWorker2 = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = false };


        // Get a handle to an application window.
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll")]
        static extern byte VkKeyScan(char ch);

        [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
        static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();


        public class BrowserLocation
        {
            /// <summary>
            /// Structure to hold the details regarding a browed location
            /// </summary>
            public struct URLDetails
            {
                /// <summary>
                /// URL (location)
                /// </summary>
                public String URL;

                /// <summary>
                /// Document title
                /// </summary>
                public String Title;
            }

            #region Internet Explorer

            // requires the following DLL added as a reference:
            // C:\Windows\System32\shdocvw.dll

            /// <summary>
            /// Retrieve the current open URLs in Internet Explorer
            /// </summary>
            /// <returns></returns>
            public static URLDetails[] InternetExplorer()
            {
                System.Collections.Generic.List<URLDetails> URLs = new System.Collections.Generic.List<URLDetails>();
                var shellWindows = new SHDocVw.ShellWindows();
                foreach (SHDocVw.InternetExplorer ie in shellWindows)
                    URLs.Add(new URLDetails() { URL = ie.LocationURL, Title = ie.LocationName });
                return URLs.ToArray();
            }

            #endregion

            #region Firefox
            // This requires NDde
            // http://ndde.codeplex.com/

            public static URLDetails[] Firefox()
            {
                NDde.Client.DdeClient dde = new NDde.Client.DdeClient("Firefox", "WWW_GetWindowInfo");
                try
                {
                    dde.Connect();
                    // Title and url is created here, problem is here..anying :P
                    String url = dde.Request("URL", Int32.MaxValue);
                    dde.Disconnect();

                    Int32 stop = url.IndexOf('"', 1);
                    return new URLDetails[]{
                new URLDetails()
                {
                    URL = url.Substring(1, stop - 1),
                    Title = url.Substring(stop + 3, url.Length - stop - 8)
                }
            };
                }
                catch (Exception)
                {
                    return null;
                }
            }
            #endregion
        }


        /******************* Worker HTTP Sniffer ****************/
        private void loadHttpSniffer_Work(object sender, DoWorkEventArgs e)
        {
            // First lets se if Firefox is running
            // Regex 
//            var regex = new Regex(@"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?");
            var regex = new Regex("(?<=(file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)[^/]+");
            int browserCounter = 0;
            while (true)
            {
                Thread.Sleep(1000);
                foreach (Process runningProcess in Process.GetProcesses())
                {
                    var processName = runningProcess.ProcessName;
                    // *** Internet Explorer URL Sniffing ***//

                    try
                    {
                        if (processName == "iexplore")
                        {
                            (new List<BrowserLocation.URLDetails>(BrowserLocation.InternetExplorer())).ForEach(u =>
                            {
                                browserCounter++;
                                urlTitle = u.Title;
                                rawUrl = u.URL;

                                var match = regex.Match(u.URL);

                                if (match.Success)
                                {
                                    name = match.Groups[5].Value;
                                    urlNameListerner = name;
                                }
                            });
                        }
                    }
                    catch (Exception)
                    {
                        Debug.Write("error");
                    }
                    // *** Internet Explorer URL Sniffing ***//



                    // *** Firefox URL Sniffing ***//

                    if (processName == "firefox")
                    {
                        try
                        {
                            (new List<BrowserLocation.URLDetails>(BrowserLocation.Firefox())).ForEach(u =>
                            {
                                browserCounter++;
                                rawUrl = u.URL;
                                // Here is where I get the title
                                urlTitle = u.Title; 

                                var match = regex.Match(u.URL);
                                if (match.Success)
                                {
                                    name = match.Groups[1].Value;
                                    urlNameListerner = name;
                                }
                            });

                        }
                        catch (Exception ex)
                        {
                            Debug.Write("Error Firefox: " + ex);
                        }
                    }
                    // *** Firefox URL Sniffing ***//               
                }
                if (browserCounter <= 0)
                {
                    Console.WriteLine("No browser..sniff");
                    name = null;
                }
            }
        }



        public void startWorkers()
        {
            if (!insaneWorker.IsBusy)
            {
                insaneWorker.DoWork += loadHttpSniffer_Work;
                insaneWorker.RunWorkerAsync();
            }
        }


        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            IntPtr handle = IntPtr.Zero;
            StringBuilder Buff = new StringBuilder(nChars);
            handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }


        // Strubg kusterber
        private string _urlNameListerner;
        public string urlNameListerner
        {
            get { return _urlNameListerner; }
            set
            {
                int counter = 0;
                _urlNameListerner = value;

                // Downloading url and scan for bad words
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                WebClient wc = new WebClient();
                byte[] raw = wc.DownloadData(rawUrl);
                string webData = System.Text.Encoding.UTF8.GetString(raw);

                Regex wordFilter = new Regex(@"\b(Sitemap|Legal Documentation|Aftonbladet)\b", RegexOptions.IgnoreCase);
                var matchResults = wordFilter.Match(webData);

                /**** Firefox ****/
                string windowTitle = GetActiveWindowTitle();
                Regex findFirefox = new Regex(@"Mozilla Firefox", RegexOptions.IgnoreCase);
                var matchFirefox = findFirefox.Match(windowTitle);

                // Kontrollerar om anvädaren använder firefox
                if (matchFirefox.Success)
                {
                    // Counting results..boring
                    while (matchResults.Success)
                    {
                        counter++;
                        matchResults = matchResults.NextMatch();
                    }

                    // ´Limiting badwords...bububäbä
                    if (counter > 2)
                    {
                        // An warning box will apear..somewhere
                        Console.WriteLine("Bad URL..Warning");

                        // Send the user to home address
                        InputSimulator.SimulateKeyPress(VirtualKeyCode.BROWSER_HOME);
                    }
                }
                /**** Firefox ****/


                 /**** IE ****/
                 IntPtr ie = FindWindow(null, urlTitle + " - Windows Internet Explorer");
                 IntPtr chrome = FindWindow(null, urlTitle + " - Google Chrome");

                 if (!ie.Equals(IntPtr.Zero))
                 {
                     while (matchResults.Success)
                     {
                         counter++;
                         matchResults = matchResults.NextMatch();
                     }

                     // Limiting bad words agiaan
                     if (counter > 2)
                     {
                         // En varnings ruta skall visas här
                         Console.WriteLine("Bad URL..Warning");

                         // Send the user to home address
                         InputSimulator.SimulateKeyPress(VirtualKeyCode.BROWSER_HOME);
                     }
                 }
                 /**** IE ****/

            }
        }


        public MainWindow()
        {
            InitializeComponent();

            // Start background stuff
            startWorkers(); 
        }
    }
}

Open in new window


I know..its alot :S..but maybe it helps?
Thanks
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38780683
Where are you getting the DdeClient from?
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 1

Author Comment

by:chugarah
ID: 38780949
Hmmm?  Well I got it from Visual studio NuGet package manager, just searched for it and downloaded it from there.

NuGet
0
 
LVL 1

Author Comment

by:chugarah
ID: 38780954
The strange thing, it works when using IE but not firefox, tried also to change encoding to something else (in the webbrowser). Its set to Unicode(UTF-8) by default.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 38783048
I downloaded the source code for the NDde project from CodePlex, and I found that it uses ASCII encoding, and not UTF-8 or Unicode:

http://ndde.codeplex.com/

Public/Advanced/DdeContext:

       private Encoding _Encoding      = Encoding.ASCII; // This is a cached DdemlContext property.

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38815906
Were you able to find a solution?
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now