65.9K
CodeProject is changing. Read more.
Home

WinForms.ColorDialog in WPF

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Sep 15, 2011

CPOL
viewsIcon

43444

downloadIcon

827

System.Windows.Forms.ColorDialog in a small WPF project TextEditor.

Introduction

This article demonstrates how to use System.Windows.Forms.ColorDialog in a WPF project. Why you may ask, simply because one can and must try...

Background

For not wanting to design a UserControl nor an extra project for my solution, I started an extensive search for a simplistic solution and thus I created the following. It also demonstrates how to use WinForms components in a WPF solution.

Using the code

To demonstrate, I've made a small TextEditor. I'll show how to change the foreground / background color of the selected text within a RichTextBox.

Sample.PNG

  1. Create a new solution with a WPF project named TextEditor
  2. SolutionExplore.png

    [Solution Explorer]
  3. Add references System.Windows.Forms.dll and System.Drawing.dll. Both can be found in the following directory: C:\Windows\Microsoft.NET\Framwork\v2.0.50727\.
  4. Images
  5. Add a folder to the project and name it Images, then add the images needed for the toolbar.

  6. Document Manager
  7. Add a class to the project and name it DocumentManager.cs, then add a few methods.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using Microsoft.Win32;
     
    namespace TextEditor
    {
        class DocumentManager
        {
            private string _currentFile;
            private RichTextBox _textBox;
    
            public DocumentManager(RichTextBox textBox)
            {
                _textBox = textBox;
            }
    
            public void ApplyToSelection(DependencyProperty property, object value)
            {
                _textBox.Selection.ApplyPropertyValue(property, value);
            }
    
            public bool OpenDocument()
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == true)
                {
                    _currentFile = dlg.FileName;
                    using (Stream stream = dlg.OpenFile())
                    {
                        TextRange range = new TextRange(
                            _textBox.Document.ContentStart,
                            _textBox.Document.ContentEnd);
                        range.Load(stream, DataFormats.Rtf);
                    }
                    return true;
                }
                return false;
            }
    
            public bool SaveDocument()
            {
                if (string.IsNullOrEmpty(_currentFile)) return SaveDocumentAs();
                else
                {
                    using (Stream stream = new FileStream(_currentFile, FileMode.Create))
                    {
                        TextRange range = new TextRange(
                            _textBox.Document.ContentStart,
                            _textBox.Document.ContentEnd);
                        range.Save(stream, DataFormats.Rtf);
                    }
                    return true;
                }
            }
    
            public bool SaveDocumentAs()
            {
                SaveFileDialog dlg = new SaveFileDialog();
                if (dlg.ShowDialog() == true)
                {
                    _currentFile = dlg.FileName;
                    return SaveDocument();
                }
                return false;
            }
    
            public void NewDocument()
            {
                _currentFile = null;
                _textBox.Document = new FlowDocument();
            }
        }
    }
  8. MainWindow.xml
  9. <Window x:Class="TextEditor.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" 
            Height="350" 
            Width="525">
        <DockPanel>
            <ToolBarTray DockPanel.Dock="top">
                <ToolBar >
                    <Button x:Name="highlight" Click="Highlight_Click">
                        <Image Source="Images\text_highlight.png" />
                    </Button>
                    <Button x:Name="color" Click="Color_Click">
                        <Image Source="Images\text_Color.png" />
                    </Button>
                </ToolBar>
            </ToolBarTray>
            <RichTextBox x:Name="body"
                         SelectionChanged="body_SelctionChanged"
                         SpellCheck.IsEnabled="True"
                         AcceptsReturn="True"
                         AcceptsTab="True"
                         BorderThickness="0 2 0 0" />
        </DockPanel>
    </Window>
  10. MainWindow.xaml.cs
  11. usisng 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;
    
    namespace TextEditor
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            private DocumentManager _documentManager;
            public MainWindow()
            {
                InitializeComponent();
    
                // Insert code required on object creation below this point.
                _documentManager = new DocumentManager(body);
            }
    
            private void body_SelctionChanged(object seder, RoutedEventArgs e)
            {
                //update the tool bar
            }
    
            private void Highlight_Click(object sender, RoutedEventArgs e)
            {
                SolidColorBrush scb = new SolidColorBrush();
                _documentManager.ApplyToSelection(
                                      TextBlock.ForegroundProperty, 
                                      new SolidColorBrush(colorPicker())
                                      );
            }
            private void Color_Click(object sender, RoutedEventArgs e)
            {
                _documentManager.ApplyToSelection(
                                      TextBlock.BackgroundProperty, 
                                      new SolidColorBrush(colorPicker())
                                      );
            }
    
            private System.Windows.Media.Color colorPicker()
            {
                System.Windows.Forms.ColorDialog colorDialog = 
                           new System.Windows.Forms.ColorDialog();
                colorDialog.AllowFullOpen = true;
                colorDialog.ShowDialog();
    
                System.Windows.Media.Color col = new System.Windows.Media.Color();
                col.A = colorDialog.Color.A;
                col.B = colorDialog.Color.B;
                col.G = colorDialog.Color.G;
                col.R = colorDialog.Color.R;
                return col;
            }
        }
    }

Points of Interest

I've learned that one doesn't need to discard old libraries.