chugarah
asked on
C# WPF URL/TItle from Firefox Swedish letters
I am using this code to get current URL from Firefox
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/
DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
dde.Disconnect();
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/
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?
ASKER
Yes, I think the same. its wery strange.. Will post the whole code most be something I have done somewhere..?
I know..its alot :S..but maybe it helps?
Thanks
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\&%_\./-~-]*)?");
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();
}
}
}
I know..its alot :S..but maybe it helps?
Thanks
Where are you getting the DdeClient from?
ASKER
ASKER
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Were you able to find a solution?