Link to home
Start Free TrialLog in
Avatar of r3nder
r3nderFlag for United States of America

asked on

I need help with a class and a new window

I have a windows form I need the frmWarning to show when a dirty word is typed globally (code attached) then I call the form on the _click method it comes up weather it is true or not - so does the message box (if enabled) - both on enter or search - I am also trying to replace the text with ****** or ####### - see interceptKeys.
[b]frmMain[/b]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Security;
using System.Runtime.InteropServices;


namespace Nomad
{
    public partial class frmMain : Form
    {
        BadWordFilter newBadwordFilter;
        
        public frmMain()
        {
            InitializeComponent();
            comboBox1.SelectedIndex = 0;
            newBadwordFilter = BadWordFilter.Instance;
            InterceptKeys.AttachHook();
            //bool a = which one
            //a = newBadwordFilter.IsCleanString("Fuck");//to check
            //a = newBadwordFilter.IsCleanString("Duck");//to check
            int c = 0;
            


        }
        
   



        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            webBrowser1.Navigate(new Uri(comboBox1.SelectedItem.ToString()));

        }

        private void btnStartLP_Click(object sender, EventArgs e)
        {

            var proc = new Process();
            proc.StartInfo.FileName = "liveperson/hc.exe";
            proc.StartInfo.Arguments = "-v -s -a";
            proc.Start();
            proc.WaitForExit();
            var exitCode = proc.ExitCode;
            proc.Close();
        }
        ///////////////////////////////Knowledge  Base//////////////////
        /// <summary>
        /// Question answer Pair
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void btnSearchKnowledge_Click(object sender, EventArgs e)
        {
            char[] delimiters = new char[] { ',', ' ' };
            string[] keywords = txtBoxKnowledgeQuestion.Text.Split(delimiters, [StringSplitOptions.RemoveEmptyEntries);

            XmlDocument doc = new XmlDocument();
            doc.Load("XMLQandA.xml");

            XmlElement root = doc.DocumentElement;

            XmlNodeList nodeList = root.SelectNodes("/messages/messageItem");

            foreach (XmlNode node in nodeList)
            {
                bool hasAllWords = true;
                bool hasAnyWord = false;
                foreach (string keyword in keywords)
                {
                    if (node.InnerText.Contains(keyword))
                    {
                        hasAnyWord = true;
                    }
                    else hasAllWords = false;
                }


                if (hasAllWords)
                {
                    // add the node to found-items-list         
                    lstBoxQA.Items.Add(node.InnerText);
                    lstBoxQA.Items.Add("======================");
                    //lstBoxQA.Items.AddRange(node.InnerText);
                    return;

                }
                if (hasAnyWord)
                {

                    //process found-items-list
                    lstBoxQA.Items.Add(node.InnerText);
                    lstBoxQA.Items.Add("======================");
                    //lstBoxQA.Items.AddRange(node.InnerText);
                }
                

                

            }
           [b] frmWarning frm = new frmWarning();
            frm.Show();
            //MessageBox.Show("You have typed a word that has been deemed \n inapropriate - it will be blanked out - Next time an email \n will be sent to HR and IT to have your access cut off");[/b]
            int c = 1;
        }

        private void btnEVid_Click(object sender, EventArgs e)
        {
            webBEVid.Navigate(new Uri("http://174.132.177.50:81/FutureViewWorkingCopy/OperatorAdministration/Login.aspx"));
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnLogon_Click(object sender, EventArgs e)
        {
            
            
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            
        }

        private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            
        }

        private void btnCamp_Click(object sender, EventArgs e)
        {
            webBrowser2.Navigate(new Uri("http://et2app01/Ensercle/index.htm"));
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            lstBoxQA.Items.Clear();
            txtBoxKnowledgeQuestion.Clear();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            InterceptKeys.DetachHook();
        }
        
        
    }
}
[b]InterceptKeys classs[/b]
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Linq;



namespace Nomad
{
    class InterceptKeys
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;
        private static StringBuilder statement = new StringBuilder();
        private static BadWordFilter filter = BadWordFilter.Instance;

        static InterceptKeys()
        {

        }

        
        public static void AttachHook()
        {
            _hookID = SetHook(_proc);
        }
        

        public static void DetachHook()
        {
            UnhookWindowsHookEx(_hookID);
        }
        


        
        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
            
        {
             if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                if (vkCode > 64 && vkCode < 91)
                {
                    statement.Append((Keys)vkCode);
                }
                else if (vkCode == 32)
                {
                    statement.Append(" ");
                }


                if (((Keys)vkCode).Equals(Keys.Return))
                {
                    
                    if (!filter.IsCleanString(statement.ToString()))
                    {

                        
                        statement = new StringBuilder();
                        //MessageBox.Show("the text is:" + statement.ToString());
                        
                        
                        MessageBox.Show("you have typed a word that has been deemed \n inapropriate - it will be blanked out - Next time an email \n will be sent to HR and IT to have your access cut off" + statement.ToString());
                        //statement.Replace(statement.ToString(), "*******");
                        int c = 1;
                                
                        
                        
                    }

                    
                  
                    
                }
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        
        }
        //public event EventHandler Igotthebadword;
        //public void Raise()
        //{
        //    if (statement != null)
        //    {
        //        MessageBox.Show("you have typed a word that has been deemed /n inapropriate - it will be blanked out - Next time an email /n will be sent to HR and IT to have your access cut off");
        //        int c = 1;
        //    }
            

        //}



        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);


        
    }
}
[b]I also use a badwordFilter[/b]
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

/// <summary>
/// Summary description for BadWordFilter
/// </summary>
public class BadWordFilter
{

    /// <summary>
    /// Private constructor and instantiate the list of regex
    /// </summary>
    private BadWordFilter()
    {
        //
        // TODO: Add constructor logic here
        //
        Patterns = new List<Regex>();
    }

    /// <summary>
    /// The patterns
    /// </summary>
    static List<Regex> Patterns;

    private static BadWordFilter m_instance = null;

    public static BadWordFilter Instance
    {
        get
        {
            if (m_instance == null)
                m_instance = CreateBadWordFilter("listofwords.xml");

            return m_instance;
        }
    }

    /// <summary>
    /// Create all the patterns required and add them to the list
    /// </summary>
    /// <param name="badWordFile"></param>
    /// <returns></returns>
    protected static BadWordFilter CreateBadWordFilter(string badWordFile)
    {
        BadWordFilter filter = new BadWordFilter();
        XmlDocument badWordDoc = new XmlDocument();
        badWordDoc.Load(badWordFile);

        //Loop through the xml document for each bad word in the list
        for (int i = 0; i < badWordDoc.GetElementsByTagName("word").Count; i++)
        {
            //Split each word into a character array
            char[] characters = badWordDoc.GetElementsByTagName("word")[i].InnerText.ToCharArray();

            //We need a fast way of appending to an exisiting string
            StringBuilder patternBuilder = new StringBuilder();

            //The start of the patterm
            patternBuilder.Append("(");

            //We next go through each letter and append the part of the pattern.
            //It is this stage which generates the upper and lower case variations
            for (int j = 0; j < characters.Length; j++)
            {
                patternBuilder.AppendFormat("[{0}|{1}][\\W]*", characters[j].ToString().ToLower(), characters[j].ToString().ToUpper());
            }

            //End the pattern
            patternBuilder.Append(")");

            //Add the new pattern to our list.
            Patterns.Add(new Regex(patternBuilder.ToString()));
        }
        return filter;
    }

    /// <summary>
    /// The function which returns the manipulated string
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public string GetCleanString(string input)
    {
        for (int i = 0; i < Patterns.Count; i++)[/i]
        {
            //In this instance we actually replace each instance of any bad word with a specified string.
            input = Patterns[i].Replace(input, "****");
        }

        //return the manipulated string
        return input;
    }

    public bool IsCleanString(string input)
    {
        for (int i = 0; i < Patterns.Count; i++)
        {
            //In this instance we actually replace each instance of any bad word with a specified string.
            if (Patterns[i].IsMatch(input))
            {
                return false;
            }
        }

        //return the manipulated string
        return true;
    }
}
[b]frmWarning[/b]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Security;
using System.Runtime.InteropServices;

namespace Nomad
{
    public partial class frmWarning : Form
    {
        public frmWarning()
        {
            InitializeComponent();
            
            InterceptKeys.AttachHook();
           // lblWarningWord.Text = InterceptKeys.AttachHook(;
                //statement.ToString();
        }

        private void btnWarning_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

    }
}
[b]the xml[/b]
is structured as so
<?xml version="1.0" encoding="utf-8" ?>
<words>
  <word>a dirty word</word>
</words>
[/i]

Open in new window

Avatar of Ravi Vaddadi
Ravi Vaddadi
Flag of United States of America image

What is your question?
Avatar of r3nder

ASKER

I have a windows form - I need the frmWarning to show when a dirty word is typed globally (code attached) (interceptkeys)
When I call the form on the _click method it comes up weather it is true or not - so does the message box (if enabled) - both on enter or search and if I use a messagebox it disappears just as quickly as it shows- (frmMain and interceptkeys)
I am also trying to replace the text with ****** or ####### - see interceptKeys. -
I need help making it come up only when true and adding the offensive word to the frmWarning then replacing or blanking out the offensive word
Let me understand. When you say "typed globally" is it on any application? or any screen in your application?
Avatar of r3nder

ASKER

globally means any application - ex: if I open notepad and type a dirty word (like the F word) the frmWarning shows
Avatar of r3nder

ASKER

the code for globally is interceptkeys.cs below

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Linq;



namespace Nomad
{
    class InterceptKeys
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;
        private static StringBuilder statement = new StringBuilder();
        private static BadWordFilter filter = BadWordFilter.Instance;

        static InterceptKeys()
        {

        }

       
        public static void AttachHook()
        {
            _hookID = SetHook(_proc);
        }
       

        public static void DetachHook()
        {
            UnhookWindowsHookEx(_hookID);
        }
       


       
        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
           
        {
             if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                if (vkCode > 64 && vkCode < 91)
                {
                    statement.Append((Keys)vkCode);
                }
                else if (vkCode == 32)
                {
                    statement.Append(" ");
                }


                if (((Keys)vkCode).Equals(Keys.Return))
                {
                   
                    if (!filter.IsCleanString(statement.ToString()))
                    {

                       
                        statement = new StringBuilder();
                        //MessageBox.Show("the text is:" + statement.ToString());
                       
                       
                        MessageBox.Show("you have typed a word that has been deemed \n inapropriate - it will be blanked out - Next time an email \n will be sent to HR and IT to have your access cut off" + statement.ToString());
                        //statement.Replace(statement.ToString(), "*******");
                        int c = 1;
                               
                       
                       
                    }

                   
                 
                   
                }
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
       
        }
        //public event EventHandler Igotthebadword;
        //public void Raise()
        //{
        //    if (statement != null)
        //    {
        //        MessageBox.Show("you have typed a word that has been deemed /n inapropriate - it will be blanked out - Next time an email /n will be sent to HR and IT to have your access cut off");
        //        int c = 1;
        //    }
           

        //}



        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);


       
    }
}
What kind of project are you using for this? Your application need to be running always to listen and intercept any keyboard activities right?
Avatar of r3nder

ASKER

yes it is a windows form that has tools we use to communicate to customers - when the app is off then this is off
I mean where is you entry point? You are launching you windows application and hiding the form to listen? Could you elaborate on you approach please. I see the code but  somethings are not really clear like who would launching your main form? Your interception would start working only if the application is launched and the main form is launched right?
Avatar of r3nder

ASKER

correct in the FrmMain body code attached and bolded

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Security;
using System.Runtime.InteropServices;

namespace Nomad
{
    public partial class frmMain : Form
    {
        BadWordFilter newBadwordFilter; - this calls the class with the xml with the bad words
       
        public frmMain()
        {
            InitializeComponent();
            comboBox1.SelectedIndex = 0;
            newBadwordFilter = BadWordFilter.Instance;
            InterceptKeys.AttachHook(); this calls the class to look for keystrokes
           //bool a = which one
            //a = newBadwordFilter.IsCleanString("Fuck");//to check
            //a = newBadwordFilter.IsCleanString("Duck");//to check
            int c = 0;
           

        }
       
   
 
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            webBrowser1.Navigate(new Uri(comboBox1.SelectedItem.ToString()));
        }
        private void btnStartLP_Click(object sender, EventArgs e)
        {
            var proc = new Process();
            proc.StartInfo.FileName = "liveperson/hc.exe";
            proc.StartInfo.Arguments = "-v -s -a";
            proc.Start();
            proc.WaitForExit();
            var exitCode = proc.ExitCode;
            proc.Close();
        }
        ///////////////////////////////Knowledge  Base//////////////////
        /// <summary>
        /// Question answer Pair
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///
        private void btnSearchKnowledge_Click(object sender, EventArgs e)
        {
            char[] delimiters = new char[] { ',', ' ' };
            string[] keywords = txtBoxKnowledgeQuestion.Text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLQandA.xml");
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodeList = root.SelectNodes("/messages/messageItem");
            foreach (XmlNode node in nodeList)
            {
                bool hasAllWords = true;
                bool hasAnyWord = false;
                foreach (string keyword in keywords)
                {
                    if (node.InnerText.Contains(keyword))
                    {
                        hasAnyWord = true;
                    }
                    else hasAllWords = false;
                }

                if (hasAllWords)
                {
                    // add the node to found-items-list        
                    lstBoxQA.Items.Add(node.InnerText);
                    lstBoxQA.Items.Add("======================");
                    //lstBoxQA.Items.AddRange(node.InnerText);
                    return;
                }
                if (hasAnyWord)
                {
                    //process found-items-list
                    lstBoxQA.Items.Add(node.InnerText);
                    lstBoxQA.Items.Add("======================");
                    //lstBoxQA.Items.AddRange(node.InnerText);
                }
               
               
            }
            frmWarning frm = new frmWarning();
            frm.Show();
            //MessageBox.Show("You have typed a word that has been deemed \n inapropriate - it will be blanked out - Next time an email \n will be sent to HR and IT to have your access cut off");
            int c = 1;
       }
        private void btnEVid_Click(object sender, EventArgs e)
        {
            webBEVid.Navigate(new Uri("http://174.132.177.50:81/FutureViewWorkingCopy/OperatorAdministration/Login.aspx"));
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        }
        private void btnLogon_Click(object sender, EventArgs e)
        {
           
           
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
           
        }
        private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
           
        }
        private void btnCamp_Click(object sender, EventArgs e)
        {
            webBrowser2.Navigate(new Uri("http://et2app01/Ensercle/index.htm"));
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            lstBoxQA.Items.Clear();
            txtBoxKnowledgeQuestion.Clear();
        }
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
           InterceptKeys.DetachHook(); this stops it
        }
       
       
    }
}

       
   

I got that. But my point is how is the main form launched.. i.e.. Main method of your program.cs calls the frmMain.
Now point is how would you application run. It is an executable rt so how it would be run? who will run it?
Avatar of r3nder

ASKER

it is an exe - the employee will run it - because it has all the tools for what we need in it
Does nt this work?
if (hasAnyWord)
{
frmWarning frm = new frmWarning();
 DialogResult  result =  frm.ShowDialog();
}
Avatar of r3nder

ASKER

hasAnyWord is for the listbox and the search of a knowledge base so it is not going to find it if you click the search button.
but
if you hit enter it does see it and the messagebox shows and disappears real quick
Avatar of r3nder

ASKER

currently if you click search with the word cost in the textbox frmWarning  comes up with the form and if you hit enter the messagebox comes up and distappears real quick
Once you intercept the keyboard event, you will have to execute your action and let the system handle it. In this case I dont think that is happening though. check this article for more information on how to capture system events.

http://msdn.microsoft.com/en-us/library/ms644960
Avatar of r3nder

ASKER

the system cant handle it the system has to return it and throw the frm once it found a dirty word
.
Yes. that is your interception. Please read the article. You will get an idea of what I am talking about.
Avatar of r3nder

ASKER

but the code I have allready does most of this and there is nothing really new
You must place a global hook procedure in a DLL separate from the application installing the hook procedure. The installing application must have the handle to the DLL module before it can install the hook procedure. To retrieve a handle to the DLL module, call the LoadLibrary function with the name of the DLL. After you have obtained the handle, you can call the GetProcAddress function to retrieve a pointer to the hook procedure
Avatar of r3nder

ASKER

I have already done that
Avatar of r3nder

ASKER

All I need is the frmWarning to come up when a dirty word is typed - if the formMain (main application) is open and I type the f word or cost or anything in the knowledge base search for testing and hit enter key on the keyboard the messagebox in the interceptkeys.cs opens for a split second and is gone. If I hit the seach button the same thing happens. - Now if I have the app open and notepad open and type in notepad the f word and hit the enter key it works fine the alert comes up no problem and stays and if i type duck and hit enter no messagebox. so that is correct but if I hit the search button, no matter what I type cost, duck or the f word the frmWarning executes
"Search" button on your application?
Avatar of r3nder

ASKER

yes Sri
Could you try a messagebox in place of frmWarning.Show and see if the same thing happens. Just for a test.
Avatar of r3nder

ASKER

works now - is there some way I can pass the statement.to string to the frmWarning and use the form
that you can see


Avatar of r3nder

ASKER

and clear or mask the word that was typed
ASKER CERTIFIED SOLUTION
Avatar of Ravi Vaddadi
Ravi Vaddadi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Could you please post the code?
Avatar of r3nder

ASKER

I havent written the code yet