?
Solved

C# WPF URL/TItle from Firefox Swedish letters

Posted on 2013-01-13
7
Medium Priority
?
868 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 1500 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Suggested Courses

770 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