diff --git a/TextLocator/App.xaml.cs b/TextLocator/App.xaml.cs
index e248e7bcf207b1fd2d7ca0be8f572a64ba6e4a87..664a990e355e052c466ca69c6131e54b4dd75b2a 100644
--- a/TextLocator/App.xaml.cs
+++ b/TextLocator/App.xaml.cs
@@ -1,6 +1,9 @@
using Hardcodet.Wpf.TaskbarNotification;
using log4net;
using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
@@ -10,6 +13,7 @@ using TextLocator.Core;
using TextLocator.Enums;
using TextLocator.Factory;
using TextLocator.Service;
+using TextLocator.SingleInstance;
using TextLocator.Util;
namespace TextLocator
@@ -17,20 +21,50 @@ namespace TextLocator
///
/// App.xaml 的交互逻辑
///
- public partial class App : Application
+ public partial class App : Application, ISingleInstanceApp
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
+ ///
+ /// 入口函数
+ ///
+ [STAThread]
+ public static void Main()
+ {
+ Assembly assembly = Assembly.GetExecutingAssembly();
+ string uniqueName = string.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name);
+ if (SingleInstance.InitializeAsFirstInstance(uniqueName)) {
+ var app = new App();
+ app.InitializeComponent();
+ app.Run();
+
+ SingleInstance.Cleanup();
+ }
+ }
+
+ ///
+ /// 信号外部命令行参数
+ ///
+ ///
+ ///
+ public bool SignalExternalCommandLineArgs(IList args)
+ {
+ if (this.MainWindow.WindowState == WindowState.Minimized)
+ {
+ this.MainWindow.WindowState = WindowState.Normal;
+ }
+
+ this.MainWindow.Activate();
+
+ return true;
+ }
+
// 托盘图标
private static TaskbarIcon _taskbar;
public static TaskbarIcon Taskbar { get => _taskbar; set => _taskbar = value; }
- // 单实例
- private Mutex _mutex;
-
public App()
{
-
// 初始化线程池大小
AppCore.SetThreadPoolSize();
@@ -39,6 +73,9 @@ namespace TextLocator
// 初始化文件服务引擎
InitFileInfoServiceEngine();
+
+ // 初始化窗口状态尺寸
+ CacheUtil.Put("WindowState", WindowState.Normal);
}
///
@@ -47,25 +84,6 @@ namespace TextLocator
///
protected override void OnStartup(StartupEventArgs e)
{
- // 互斥
- _mutex = new Mutex(true, "TextLocator", out bool isNewInstance);
- // 是否启动新实例
- if (!isNewInstance)
- {
- // 找到已经在运行的实例句柄(给出你的窗体标题名 “XXX影院”)
- IntPtr hWndPtr = FindWindow(null, "文本搜索定位器");
-
- // 还原窗口
- _ = IsIconic(hWndPtr) ? ShowWindow(hWndPtr, SW_RESTORE) : ShowWindow(hWndPtr, SW_SHOW);
-
- // 激活窗口
- SetForegroundWindow(hWndPtr);
-
- // 退出当前实例
- AppCore.Shutdown();
- return;
- }
-
// 托盘图标
_taskbar = (TaskbarIcon)FindResource("Taskbar");
@@ -93,6 +111,9 @@ namespace TextLocator
// 文件读取超时时间
AppUtil.WriteValue("AppConfig", "FileReadTimeout", AppConst.FILE_READ_TIMEOUT + "");
+
+ // 文件内容摘要切割长度
+ AppUtil.WriteValue("AppConfig", "FileContentBreviaryCutLength", AppConst.FILE_CONTENT_BREVIARY_CUT_LENGTH + "");
}
#endregion
@@ -186,46 +207,5 @@ namespace TextLocator
}
}
#endregion
-
- #region Windows API
- //ShowWindow 参数
- private const int SW_SHOW = 5;
- private const int SW_RESTORE = 9;
-
- ///
- /// 是标志性的
- ///
- /// 窗口句柄
- ///
- [DllImport("USER32.DLL", SetLastError = true, CharSet = CharSet.Auto)]
- private static extern bool IsIconic(IntPtr hWnd);
- ///
- /// 在桌面窗口列表中寻找与指定条件相符的第一个窗口。
- ///
- /// 指向指定窗口的类名。如果 lpClassName 是 NULL,所有类名匹配。
- /// 指向指定窗口名称(窗口的标题)。如果 lpWindowName 是 NULL,所有windows命名匹配。
- /// 返回指定窗口句柄
- [DllImport("USER32.DLL", SetLastError = true, CharSet = CharSet.Auto)]
- public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
-
- ///
- /// 将窗口还原,可从最小化还原
- ///
- ///
- ///
- ///
- [DllImport("USER32.DLL")]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
-
- ///
- /// 激活指定窗口
- ///
- /// 指定窗口句柄
- ///
- [DllImport("USER32.DLL")]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool SetForegroundWindow(IntPtr hWnd);
- #endregion
}
}
diff --git a/TextLocator/Core/AppConst.cs b/TextLocator/Core/AppConst.cs
index 14e97eceb7b1128d074d01b529051b7bc107b8e8..ee402f43df06f65b3e085cc7af8d850e6bf23fb4 100644
--- a/TextLocator/Core/AppConst.cs
+++ b/TextLocator/Core/AppConst.cs
@@ -14,10 +14,6 @@ namespace TextLocator.Core
///
public class AppConst
{
- ///
- /// 结果列表分页条数
- ///
- public static int MRESULT_LIST_PAGE_SIZE = int.Parse(AppUtil.ReadValue("AppConfig", "ResultListPageSize", "100"));
///
/// 文件读取超时时间,单位:秒
///
@@ -27,17 +23,30 @@ namespace TextLocator.Core
///
public static int FILE_SIZE_LIMIT = int.Parse(AppUtil.ReadValue("AppConfig", "FileSizeLimit", "200000000"));
///
+ /// 文件内容摘要切割长度
+ ///
+ public static int FILE_CONTENT_BREVIARY_CUT_LENGTH = int.Parse(AppUtil.ReadValue("AppConfig", "FileContentBreviaryCutLength", "120"));
+ ///
+ /// 结果列表分页条数
+ ///
+ public static int MRESULT_LIST_PAGE_SIZE = int.Parse(AppUtil.ReadValue("AppConfig", "ResultListPageSize", "100"));
+ ///
/// 缓存池容量
///
public static int CACHE_POOL_CAPACITY = int.Parse(AppUtil.ReadValue("AppConfig", "CachePoolCapacity", "100000"));
+ ///
+ /// 索引更新任务间隔时间,单位:分
+ ///
+ public static int INDEX_UPDATE_TASK_INTERVAL = int.Parse(AppUtil.ReadValue("AppConfig", "IndexUpdateTaskInterval", "10"));
+
///
/// 启用索引更新任务,默认启用
///
public static bool ENABLE_INDEX_UPDATE_TASK = bool.Parse(AppUtil.ReadValue("AppConfig", "EnableIndexUpdateTask", "True"));
///
- /// 索引更新任务间隔时间,单位:分
+ /// 启用预览摘要
///
- public static int INDEX_UPDATE_TASK_INTERVAL = int.Parse(AppUtil.ReadValue("AppConfig", "IndexUpdateTaskInterval", "10"));
+ public static bool ENABLE_PREVIEW_SUMMARY = bool.Parse(AppUtil.ReadValue("AppConfig", "EnablePreviewSummary", "False"));
///
/// 最小工作线程(CPU线程数 * 2)
@@ -93,7 +102,7 @@ namespace TextLocator.Core
///
/// 匹配空白和换行
///
- public static readonly Regex REGEX_LINE_BREAKS_WHITESPACE = new Regex(@" |\r\r|\n\n|┄|\s");
+ public static readonly Regex REGEX_LINE_BREAKS_WHITESPACE = new Regex(@" |\r\r|\n\n|\s\s|┄");
///
/// 匹配HTML和XML标签
///
diff --git a/TextLocator/Entity/FileInfo.cs b/TextLocator/Entity/FileInfo.cs
index c1be0b1767314d3c34f95428669a1f8b79b07286..747d8ada48b486b744492e6b232bfb69ae0139f2 100644
--- a/TextLocator/Entity/FileInfo.cs
+++ b/TextLocator/Entity/FileInfo.cs
@@ -8,6 +8,13 @@ namespace TextLocator.Entity
///
public class FileInfo
{
+ // -------- 列表索引 --------
+ ///
+ /// 列表序号
+ ///
+ public int Index { get; set; }
+
+ // -------- 文件信息 --------
///
/// 文件类型
///
@@ -43,7 +50,6 @@ namespace TextLocator.Entity
///
private List keywords = new List();
public List Keywords { get => keywords; set => keywords = value; }
-
///
/// 搜索域
///
diff --git a/TextLocator/Factory/FileInfoServiceFactory.cs b/TextLocator/Factory/FileInfoServiceFactory.cs
index 4b64b9ba56a0e17df7c434c39d73675e7671081b..48a4be80b2249786ed899c9cdeae195970c1bc75 100644
--- a/TextLocator/Factory/FileInfoServiceFactory.cs
+++ b/TextLocator/Factory/FileInfoServiceFactory.cs
@@ -32,52 +32,27 @@ namespace TextLocator.Factory
///
public static string GetFileContent(string filePath)
{
- FileInfo fileInfo = new FileInfo(filePath);
+ // 读取文件内容
+ string content = String.Empty;
try
{
- // 如果文件存在
- if (fileInfo == null && !fileInfo.Exists)
- {
- throw new FileNotFoundException("文件未找到,请确认");
- }
- // 文件太大
- if (fileInfo.Length > AppConst.FILE_SIZE_LIMIT)
- {
- throw new FileBigSizeException("不支持大于 " + FileUtil.GetFileSizeFriendly(AppConst.FILE_SIZE_LIMIT) + " 的文件解析");
- }
- }
- catch (Exception ex)
- {
- log.Error(filePath + "->" + ex.Message, ex);
-
- return null;
- }
+ // 检查文件信息
+ CheckFileInfo(filePath);
- // 获取文件服务对象
- IFileInfoService fileInfoService = GetFileInfoService(FileTypeUtil.GetFileType(filePath));
+ // 获取文件服务对象
+ IFileInfoService fileInfoService = GetFileInfoService(FileTypeUtil.GetFileType(filePath));
- // 内容
- string content = "";
- // 缓存Key
- string cacheKey = MD5Util.GetMD5Hash(filePath);
+ // 获取文件内容
+ content = WaitTimeout(fileInfoService.GetFileContent, filePath);
- if (CacheUtil.Exists(cacheKey))
- {
- // 从缓存中读取
- content = CacheUtil.Get(cacheKey);
-#if DEBUG
- log.Debug(filePath + ",缓存生效。");
-#endif
+ // 特殊字符替换
+ content = AppConst.REGEX_LINE_BREAKS_WHITESPACE.Replace(content, " ");
}
- else
+ catch (Exception ex)
{
- // 读取文件内容
- content = WaitTimeout(fileInfoService.GetFileContent, filePath);
-
- // 写入缓存
- CacheUtil.Put(cacheKey, content);
+ log.Error(filePath + " -> 文件读取错误:" + ex.Message, ex);
}
-
+ // 返回
return content;
}
@@ -109,6 +84,25 @@ namespace TextLocator.Factory
throw new NotFoundFileServiceException("暂无[" + fileType.ToString() + "]服务实例, 返回默认其他类型文件服务实例");
}
}
+
+ ///
+ /// 检查文件信息
+ ///
+ /// 文件路径
+ private static void CheckFileInfo(string filePath)
+ {
+ FileInfo fileInfo = new FileInfo(filePath);
+ // 如果文件存在
+ if (fileInfo == null && !fileInfo.Exists)
+ {
+ throw new FileNotFoundException("文件未找到,请确认");
+ }
+ // 文件太大
+ if (fileInfo.Length > AppConst.FILE_SIZE_LIMIT)
+ {
+ throw new FileBigSizeException(string.Format("不支持大于 {0} 的文件解析", FileUtil.GetFileSizeFriendly(AppConst.FILE_SIZE_LIMIT)));
+ }
+ }
#endregion
#region 超时函数
@@ -130,7 +124,11 @@ namespace TextLocator.Factory
{
string obj = null;
AutoResetEvent are = new AutoResetEvent(false);
- Thread t = new Thread(delegate () { obj = method(filePath); are.Set(); });
+ Thread t = new Thread(() =>
+ {
+ obj = method(filePath);
+ are.Set();
+ });
t.Start();
Wait(t, are);
return obj;
diff --git a/TextLocator/FileInfoItem.xaml b/TextLocator/FileInfoItem.xaml
index c34611bdebdb3490a93e69f6020fc548d16d91c7..3c7ad70dda7b3024b15a193987805df301ffe675 100644
--- a/TextLocator/FileInfoItem.xaml
+++ b/TextLocator/FileInfoItem.xaml
@@ -9,7 +9,7 @@
-
+
diff --git a/TextLocator/FileInfoItem.xaml.cs b/TextLocator/FileInfoItem.xaml.cs
index 986e3031aade9eab2138c711ca63a0d00852eb8f..d9e4721702a7482e00c5af6c981cb4b41c1508b1 100644
--- a/TextLocator/FileInfoItem.xaml.cs
+++ b/TextLocator/FileInfoItem.xaml.cs
@@ -3,6 +3,8 @@ using System;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
+using System.Windows.Threading;
+using TextLocator.Core;
using TextLocator.Index;
using TextLocator.Util;
@@ -19,8 +21,7 @@ namespace TextLocator
/// 文件信息显示条目
///
/// 文件信息
- /// 搜索域
- public FileInfoItem(Entity.FileInfo fileInfo, Enums.SearchRegion searchRegion)
+ public FileInfoItem(Entity.FileInfo fileInfo)
{
InitializeComponent();
@@ -28,14 +29,14 @@ namespace TextLocator
try
{
- Refresh(fileInfo, searchRegion);
+ Refresh(fileInfo);
}
catch {
Dispatcher.InvokeAsync(() =>
{
try
{
- Refresh(fileInfo, searchRegion);
+ Refresh(fileInfo);
}
catch (Exception ex)
{
@@ -49,8 +50,7 @@ namespace TextLocator
/// 刷新数据
///
/// 文件信息
- /// 搜索域
- public void Refresh(Entity.FileInfo fileInfo, Enums.SearchRegion searchRegion)
+ public void Refresh(Entity.FileInfo fileInfo)
{
// 根据文件类型显示图标
this.FileTypeIcon.Source = FileUtil.GetFileIcon(fileInfo.FileType);
@@ -62,7 +62,7 @@ namespace TextLocator
string fileName = fileInfo.FileName;
// 显示文件名称
FileContentUtil.FillFlowDocument(this.FileName, fileName.Length > 55 ? fileName.Substring(0, 55) + "..." : fileName, (Brush)new BrushConverter().ConvertFromString("#1A0DAB"), true);
- if (searchRegion == Enums.SearchRegion.文件名和内容 || searchRegion == Enums.SearchRegion.仅文件名)
+ if (fileInfo.SearchRegion == Enums.SearchRegion.文件名和内容 || fileInfo.SearchRegion == Enums.SearchRegion.仅文件名)
{
FileContentUtil.FlowDocumentHighlight(this.FileName, Colors.Red, fileInfo.Keywords);
}
@@ -73,29 +73,64 @@ namespace TextLocator
// 获取摘要
FileContentUtil.EmptyRichTextDocument(this.ContentBreviary);
- Task.Factory.StartNew(() => {
+ Task.Factory.StartNew(async () => {
+ await Task.Delay(AppConst.MRESULT_LIST_PAGE_SIZE / 2 * fileInfo.Index);
string breviary = IndexCore.GetContentBreviary(fileInfo);
- Dispatcher.InvokeAsync(() =>
+ await Dispatcher.InvokeAsync(() =>
{
FileContentUtil.FillFlowDocument(this.ContentBreviary, breviary, (Brush)new BrushConverter().ConvertFromString("#545454"));
- if (searchRegion == Enums.SearchRegion.文件名和内容 || searchRegion == Enums.SearchRegion.仅文件内容)
+ if (fileInfo.SearchRegion == Enums.SearchRegion.文件名和内容 || fileInfo.SearchRegion == Enums.SearchRegion.仅文件内容)
{
FileContentUtil.FlowDocumentHighlight(this.ContentBreviary, Colors.Red, fileInfo.Keywords);
}
});
});
- // 词频统计
- Task.Factory.StartNew(() => {
- string matchCountDetails = IndexCore.GetMatchCountDetails(fileInfo);
- Dispatcher.InvokeAsync(() => {
- if (!string.IsNullOrWhiteSpace(matchCountDetails))
- {
- // 关键词匹配次数
- this.FileTypeIcon.ToolTip = matchCountDetails;
- }
- });
+ // 词频统计明细
+ Task.Factory.StartNew(async () => {
+ await Task.Delay(AppConst.MRESULT_LIST_PAGE_SIZE * fileInfo.Index);
+ LoadMatchCountDetails(fileInfo);
});
}
+
+ ///
+ /// 光标在文件类型图标边界移入事件(词频统计详情放在这里加载,主要是为了节省列表加载事件)
+ ///
+ ///
+ ///
+ private void FileTypeIcon_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
+ {
+ if (this.FileTypeIcon.ToolTip == null)
+ {
+ LoadMatchCountDetails(this.Tag as Entity.FileInfo);
+ }
+ }
+
+ ///
+ /// 加载词频统计详情放在这里
+ ///
+ private void LoadMatchCountDetails(Entity.FileInfo fileInfo)
+ {
+ string matchCountDetails = IndexCore.GetMatchCountDetails(fileInfo);
+ if (!string.IsNullOrWhiteSpace(matchCountDetails))
+ {
+ void Load()
+ {
+ this.FileTypeIcon.ToolTip = matchCountDetails;
+ ToolTipService.SetShowDuration(this.FileTypeIcon, 600000);
+ }
+ try
+ {
+ Load();
+ }
+ catch
+ {
+ Dispatcher.InvokeAsync(() =>
+ {
+ Load();
+ });
+ }
+ }
+ }
}
}
diff --git a/TextLocator/HotkeyWindow.xaml b/TextLocator/HotkeyWindow.xaml
index ff58c20c5be9d6ddac2e265c1aee15db90a0faed..9e462da476ea0fb5a15ab01d596a7a36ee6a3460 100644
--- a/TextLocator/HotkeyWindow.xaml
+++ b/TextLocator/HotkeyWindow.xaml
@@ -6,7 +6,7 @@
xmlns:local="clr-namespace:TextLocator"
mc:Ignorable="d"
x:Name="hotkey"
- Title="热键设置" Height="380" Width="520" WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow" ResizeMode="CanMinimize" Icon="/Resource/App.ico" Loaded="Window_Loaded" Closed="Window_Closed" >
+ Title="热键设置" Height="380" Width="520" WindowStartupLocation="CenterOwner" WindowStyle="ToolWindow" ResizeMode="CanMinimize" Icon="/Resource/App.ico" Loaded="Window_Loaded" Closed="Window_Closed" >
diff --git a/TextLocator/Index/IndexCore.cs b/TextLocator/Index/IndexCore.cs
index 3cc655b6429ccbce4a9fff81cf855664eed0ef6c..a14ccb153e41757da02f1140ef82f7b7eb13c3b1 100644
--- a/TextLocator/Index/IndexCore.cs
+++ b/TextLocator/Index/IndexCore.cs
@@ -888,7 +888,7 @@ namespace TextLocator.Index
// 获取内容
string content = AppConst.REGEX_CONTENT_PAGE.Replace(fileInfo.Preview, "");
// 缩略信息
- string breviary = AppConst.REGEX_LINE_BREAKS_WHITESPACE.Replace(content, "");
+ string breviary = AppConst.REGEX_LINE_BREAKS_WHITESPACE.Replace(content, " ");
int min = 0;
int max = breviary.Length;
diff --git a/TextLocator/MainWindow.xaml b/TextLocator/MainWindow.xaml
index d8437acdf66feed8dab8ac365c85e495949daba8..2d63d5733936c19298607e4f61f7209e163d3577 100644
--- a/TextLocator/MainWindow.xaml
+++ b/TextLocator/MainWindow.xaml
@@ -7,7 +7,7 @@
xmlns:rubyer="clr-namespace:Rubyer;assembly=Rubyer"
mc:Ignorable="d"
Title="文本搜索定位器" Width="1600" Height="900" Icon="Resource/App.ico"
- WindowStartupLocation="CenterScreen" Loaded="Window_Loaded" Closing="Window_Closing" Activated="Window_Activated">
+ WindowStartupLocation="CenterScreen" Loaded="Window_Loaded" Closing="Window_Closing" Activated="Window_Activated" SizeChanged="Window_SizeChanged" StateChanged="Window_StateChanged">
@@ -97,6 +97,8 @@
+
+
@@ -109,9 +111,9 @@
-
-
-
+
+
+
@@ -911,7 +913,7 @@
rubyer:ProgressBarHelper.Thickness="100"
rubyer:ProgressBarHelper.IsShowPercent="false"/>
-
+
diff --git a/TextLocator/MainWindow.xaml.cs b/TextLocator/MainWindow.xaml.cs
index 746d58a6232d28ba7f9ce7841df74c5e379ae80f..d30dc540033d603459f05d869832d878bb8e858e 100644
--- a/TextLocator/MainWindow.xaml.cs
+++ b/TextLocator/MainWindow.xaml.cs
@@ -12,6 +12,7 @@ using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
+using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
@@ -51,11 +52,6 @@ namespace TextLocator
///
private static volatile bool build = false;
- ///
- /// 窗口状态
- ///
- private WindowState _windowState = WindowState.Normal;
-
///
/// 数据模型
///
@@ -141,6 +137,17 @@ namespace TextLocator
HotKeySettingManager.Instance.RegisterGlobalHotKeyEvent += Instance_RegisterGlobalHotKeyEvent;
}
+ ///
+ /// 窗口激活
+ ///
+ ///
+ ///
+ private void Window_Activated(object sender, EventArgs e)
+ {
+ this.Show();
+ this.WindowState = CacheUtil.Get("WindowState");
+ }
+
///
/// 窗口关闭中,改为隐藏
///
@@ -148,20 +155,30 @@ namespace TextLocator
///
private void Window_Closing(object sender, CancelEventArgs e)
{
- _windowState = this.WindowState;
this.Hide();
e.Cancel = true;
+ CacheUtil.Put("WindowState", this.WindowState);
}
///
- /// 窗口激活
+ /// 尺寸变化
///
///
///
- private void Window_Activated(object sender, EventArgs e)
+ private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
- this.Show();
- this.WindowState = _windowState;
+ CacheUtil.Put("WindowWidth", this.Width);
+ CacheUtil.Put("WindowHeight", this.Height);
+ }
+
+ ///
+ /// 状态变化
+ ///
+ ///
+ ///
+ private void Window_StateChanged(object sender, EventArgs e)
+ {
+ CacheUtil.Put("WindowState", this.WindowState);
}
#endregion
@@ -176,7 +193,6 @@ namespace TextLocator
// 设置标题
this.Title = string.Format("{0} v{1} (开放版)", this.Title, version);
-
}
///
@@ -565,6 +581,7 @@ namespace TextLocator
}
ShowStatus("搜索处理中...");
+ ShowSearchLoading();
Thread t = new Thread(() =>
{
@@ -583,33 +600,38 @@ namespace TextLocator
if (null == searchResult || searchResult.Results.Count <= 0)
{
MessageCore.ShowWarning("没有搜到你想要的内容,请更换搜索条件。");
+ HideSearchLoading();
return;
}
// 3、---- 遍历结果
+ int index = 1;
foreach (Entity.FileInfo fileInfo in searchResult.Results)
{
if (_timestamp != timestamp)
{
return;
}
+ fileInfo.Index = index++;
Dispatcher.Invoke(() =>
{
- this.SearchResultList.Items.Add(new FileInfoItem(fileInfo, searchParam.SearchRegion));
+ this.SearchResultList.Items.Add(new FileInfoItem(fileInfo));
});
}
- // 4、---- 显示预览列表分页信息
- _viewModel.PreviewPage = string.Format("0/{0}", searchResult.Results.Count);
-
- // 5、---- 分页总数
+ // 4、---- 分页总数、显示预览列表分页信息
_viewModel.TotalCount = searchResult.Total;
+ _viewModel.PreviewPage = string.Format("0/{0}", searchResult.Results.Count);
_viewModel.PreviewSwitchVisibility = searchResult.Total > 0 ? Visibility.Visible : Visibility.Hidden;
}
catch (Exception ex)
{
log.Error("搜索错误:" + ex.Message, ex);
}
+ finally
+ {
+ HideSearchLoading();
+ }
});
t.Priority = ThreadPriority.Highest;
t.Start();
@@ -803,26 +825,37 @@ namespace TextLocator
{
try
{
- // 文件内容(预览)FileInfoServiceFactory.GetFileContent(fileInfo.FilePath, true);
+ // 方案一:通过工厂接口读取文档内容(为提高预览速度,现已放弃) -> FileInfoServiceFactory.GetFileContent(fileInfo.FilePath, true);
+ // 方案二:创建索引时写入内容到索引,预览时直接读取使用。
string content = fileInfo.Preview;
Dispatcher.InvokeAsync(() =>
{
- // 填充数据
- FileContentUtil.FillFlowDocument(PreviewFileContent, content, new SolidColorBrush(Colors.Black));
- // 默认滚动到第一页
- PreviewFileContent.CanGoToPage(1);
- ScrollViewer sourceScrollViewer = PreviewFileContent.Template.FindName("PART_ContentHost", PreviewFileContent) as ScrollViewer;
- if (sourceScrollViewer != null)
+ // 预览摘要启用
+ if (AppConst.ENABLE_PREVIEW_SUMMARY)
{
- sourceScrollViewer.ScrollToTop();
+ FlowDocument document = FileContentUtil.GetHitBreviaryFlowDocument(content, fileInfo.Keywords, Colors.Red);
+ PreviewFileContent.Document = document;
+ PreviewFileContent.CanGoToPage(1);
+ }
+ else
+ {
+ // 填充数据
+ FileContentUtil.FillFlowDocument(PreviewFileContent, content, new SolidColorBrush(Colors.Black));
+ // 默认滚动到第一页
+ PreviewFileContent.CanGoToPage(1);
+ ScrollViewer sourceScrollViewer = PreviewFileContent.Template.FindName("PART_ContentHost", PreviewFileContent) as ScrollViewer;
+ if (sourceScrollViewer != null)
+ {
+ sourceScrollViewer.ScrollToTop();
+ }
+ // 关键词高亮
+ FileContentUtil.FlowDocumentHighlight(
+ PreviewFileContent,
+ Colors.Red,
+ fileInfo.Keywords
+ );
}
- // 关键词高亮
- FileContentUtil.FlowDocumentHighlight(
- PreviewFileContent,
- Colors.Red,
- fileInfo.Keywords
- );
});
}
catch (Exception ex)
@@ -873,6 +906,26 @@ namespace TextLocator
BeforeSearch();
}
+ ///
+ /// 参数设置
+ ///
+ ///
+ ///
+ private void SettingButton_Click(object sender, RoutedEventArgs e)
+ {
+ var win = SettingWindow.CreateInstance();
+ if (!win.IsVisible)
+ {
+ win.Topmost = true;
+ win.Owner = this;
+ win.ShowDialog();
+ }
+ else
+ {
+ win.Activate();
+ }
+ }
+
///
/// 优化按钮
///
@@ -1004,6 +1057,18 @@ namespace TextLocator
///
private void IndexUpdateTask()
{
+ // 方案一:定时器
+ /*if (AppConst.INDEX_UPDATE_TASK_INTERVAL <= 5)
+ AppConst.INDEX_UPDATE_TASK_INTERVAL = 5;
+
+ System.Timers.Timer timer = new System.Timers.Timer();
+ timer.Interval = AppConst.INDEX_UPDATE_TASK_INTERVAL * 60 * 1000;
+ timer.Elapsed += Timer_Elapsed;
+ timer.AutoReset = true;
+ timer.Enabled = true;
+ timer.Start();*/
+
+ // 方案二:线程
Task.Factory.StartNew(() =>
{
try
@@ -1015,12 +1080,16 @@ namespace TextLocator
log.Info("上次任务还没执行完成,跳过本次任务。");
return;
}
- build = true;
- // 执行索引更新,扫描新文件。
- log.Info("开始执行索引更新检查。");
- BuildIndex(false, true);
+ else
+ {
+ log.Info("开始执行索引更新检查。");
- // 配置参数错误导致的bug矫正
+ build = true;
+
+ BuildIndex(false, true);
+ }
+
+ // 修复bug容错处理
if (AppConst.INDEX_UPDATE_TASK_INTERVAL <= 5)
AppConst.INDEX_UPDATE_TASK_INTERVAL = 5;
@@ -1034,6 +1103,27 @@ namespace TextLocator
});
}
+ ///
+ /// 定时器执行逻辑
+ ///
+ ///
+ ///
+ private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
+ {
+ if (build)
+ {
+ log.Info("上次任务还没执行完成,跳过本次任务。");
+ }
+ else
+ {
+ log.Info("开始执行索引更新检查。");
+
+ build = true;
+
+ BuildIndex(false, true);
+ }
+ }
+
///
/// 检查索引是否存在
///
@@ -1359,8 +1449,30 @@ namespace TextLocator
}
return keywords;
}
+ #endregion
-
+ #region Loading
+
+ ///
+ /// 显示搜索Loading
+ ///
+ private void ShowSearchLoading()
+ {
+ Dispatcher.Invoke(new Action(() =>
+ {
+ this._searchLoading.Visibility = Visibility.Visible;
+ }));
+ }
+ ///
+ /// 隐藏搜索Loading
+ ///
+ private void HideSearchLoading()
+ {
+ Dispatcher.Invoke(new Action(() =>
+ {
+ this._searchLoading.Visibility = Visibility.Collapsed;
+ }));
+ }
#endregion
}
}
diff --git a/TextLocator/NotifyIcon/NotifyIconViewModel.cs b/TextLocator/NotifyIcon/NotifyIconViewModel.cs
index 68cec865343ac06b07bc44ac92268520d06d3bc7..975fada6ae858b8ffee3f349e781becc6d73093a 100644
--- a/TextLocator/NotifyIcon/NotifyIconViewModel.cs
+++ b/TextLocator/NotifyIcon/NotifyIconViewModel.cs
@@ -46,6 +46,7 @@ namespace TextLocator.NotifyIcon
if (!win.IsVisible)
{
win.Topmost = true;
+ win.Owner = Application.Current.MainWindow;
win.ShowDialog();
}
else
@@ -72,6 +73,7 @@ namespace TextLocator.NotifyIcon
if (!win.IsVisible)
{
win.Topmost = true;
+ win.Owner = Application.Current.MainWindow;
win.ShowDialog();
}
else
diff --git a/TextLocator/Properties/AssemblyInfo.cs b/TextLocator/Properties/AssemblyInfo.cs
index a777f27d01d1e6e2eecfe7f2087f08bddcbe306a..7b8c94e39c76504c5ff152c450e134a53037f2f8 100644
--- a/TextLocator/Properties/AssemblyInfo.cs
+++ b/TextLocator/Properties/AssemblyInfo.cs
@@ -50,9 +50,9 @@ using System.Windows;
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
// 大版本,强制更新最小版本
-[assembly: AssemblyVersion("2.1.20")]
+[assembly: AssemblyVersion("2.1.28")]
// 小版本,选择更新版本
-[assembly: AssemblyFileVersion("2.1.20.1")]
+[assembly: AssemblyFileVersion("2.1.28.1")]
// Version minVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
// Version version = new Version(FileVersionInfo.GetVersionInfo(System.Windows.Forms.Application.ExecutablePath).ProductVersion);
diff --git a/TextLocator/Service/ExcelFileService.cs b/TextLocator/Service/ExcelFileService.cs
index d09ebd838ec1d15e4c25c3de6b16f400ef11db4d..1b9f9cffac145186cd2a4f364972b29c012170dc 100644
--- a/TextLocator/Service/ExcelFileService.cs
+++ b/TextLocator/Service/ExcelFileService.cs
@@ -97,7 +97,7 @@ namespace TextLocator.Service
{
for (int j = 0; j < columnCount; j++)
{
- builder.Append(sheet.Cells[i + 1, j + 1].Value + " ");
+ builder.Append(sheet.Cells[i + 1, j + 1].Value + " ");
}
builder.AppendLine();
}
@@ -199,7 +199,7 @@ namespace TextLocator.Service
int cellCount = row.LastCellNum;
for (int k = 0; k < cellCount; k++)
{
- builder.Append(row.GetCell(j) + " ");
+ builder.Append(row.GetCell(j) + " ");
}
builder.AppendLine();
}
diff --git a/TextLocator/SettingWindow.xaml b/TextLocator/SettingWindow.xaml
index 6f8dbc0943c73ab3c1d369111dfad8548822d85b..079e29c44052a637073c43650b915875ef02743e 100644
--- a/TextLocator/SettingWindow.xaml
+++ b/TextLocator/SettingWindow.xaml
@@ -7,7 +7,7 @@
xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
mc:Ignorable="d"
x:Name="hotkey"
- Title="设置" Height="380" Width="520" WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow" ResizeMode="CanMinimize" Icon="/Resource/App.ico" Loaded="Window_Loaded" Closed="Window_Closed" >
+ Title="设置" Height="380" Width="520" WindowStartupLocation="CenterOwner" WindowStyle="ToolWindow" ResizeMode="CanMinimize" Icon="/Resource/App.ico" Loaded="Window_Loaded" Closed="Window_Closed" >
@@ -59,6 +59,13 @@
+
+
+
+
+
+
+
diff --git a/TextLocator/SettingWindow.xaml.cs b/TextLocator/SettingWindow.xaml.cs
index 269c159485d85dcfce784bd60b2952cc1d67fe0b..21dc1b05b3616ac00eac774778baf9ea4722a621 100644
--- a/TextLocator/SettingWindow.xaml.cs
+++ b/TextLocator/SettingWindow.xaml.cs
@@ -70,6 +70,9 @@ namespace TextLocator
this.EnableIndexUpdateTask.IsChecked = AppConst.ENABLE_INDEX_UPDATE_TASK;
// 索引更新时间间隔
this.IndexUpdateTaskInterval.Text = AppConst.INDEX_UPDATE_TASK_INTERVAL + "";
+
+ // 启用预览内容摘要
+ this.EnablePreviewSummary.IsChecked = AppConst.ENABLE_PREVIEW_SUMMARY;
}
#region 保存并关闭
@@ -136,7 +139,6 @@ namespace TextLocator
// 启用索引更新任务
bool enableIndexUpdateTask = (bool)this.EnableIndexUpdateTask.IsChecked;
-
if (enableIndexUpdateTask)
{
// 索引更新时间间隔
@@ -160,6 +162,9 @@ namespace TextLocator
AppConst.INDEX_UPDATE_TASK_INTERVAL = indexUpdateTaskInterval;
}
+ // 启用预览内容摘要
+ bool enablePreviewSummary = (bool)this.EnablePreviewSummary.IsChecked;
+
AppConst.CACHE_POOL_CAPACITY = cachePoolCapacity;
AppUtil.WriteValue("AppConfig", "CachePoolCapacity", AppConst.CACHE_POOL_CAPACITY + "");
log.Debug("修改缓存池容量:" + AppConst.CACHE_POOL_CAPACITY);
@@ -182,6 +187,9 @@ namespace TextLocator
log.Debug("修改索引更新任务间隔时间:" + AppConst.INDEX_UPDATE_TASK_INTERVAL);
}
+ AppConst.ENABLE_PREVIEW_SUMMARY = enablePreviewSummary;
+ AppUtil.WriteValue("AppConfig", "EnableIndexUpdateTask", AppConst.ENABLE_PREVIEW_SUMMARY + "");
+
this.Close();
}
#endregion
diff --git a/TextLocator/SingleInstance/ISingleInstanceApp.cs b/TextLocator/SingleInstance/ISingleInstanceApp.cs
new file mode 100644
index 0000000000000000000000000000000000000000..50940aad3ac3b5334705df407850b5d3df6a8fae
--- /dev/null
+++ b/TextLocator/SingleInstance/ISingleInstanceApp.cs
@@ -0,0 +1,9 @@
+using System.Collections.Generic;
+
+namespace TextLocator.SingleInstance
+{
+ public interface ISingleInstanceApp
+ {
+ bool SignalExternalCommandLineArgs(IList args);
+ }
+}
diff --git a/TextLocator/SingleInstance/NativeMethods.cs b/TextLocator/SingleInstance/NativeMethods.cs
new file mode 100644
index 0000000000000000000000000000000000000000..cc3b9a4bdbdb33934ed76c24e0ee893f4bf1861b
--- /dev/null
+++ b/TextLocator/SingleInstance/NativeMethods.cs
@@ -0,0 +1,55 @@
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Security;
+
+namespace TextLocator.SingleInstance
+{
+ [SuppressUnmanagedCodeSecurity]
+ internal static class NativeMethods
+ {
+ ///
+ /// Delegate declaration that matches WndProc signatures.
+ ///
+ public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
+
+ [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
+ private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs);
+
+
+ [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
+ private static extern IntPtr _LocalFree(IntPtr hMem);
+
+
+ public static string[] CommandLineToArgvW(string cmdLine)
+ {
+ IntPtr argv = IntPtr.Zero;
+ try
+ {
+ int numArgs = 0;
+
+ argv = _CommandLineToArgvW(cmdLine, out numArgs);
+ if (argv == IntPtr.Zero)
+ {
+ throw new Win32Exception();
+ }
+ var result = new string[numArgs];
+
+ for (int i = 0; i < numArgs; i++)
+ {
+ IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
+ result[i] = Marshal.PtrToStringUni(currArg);
+ }
+
+ return result;
+ }
+ finally
+ {
+
+ IntPtr p = _LocalFree(argv);
+ // Otherwise LocalFree failed.
+ // Assert.AreEqual(IntPtr.Zero, p);
+ }
+ }
+ }
+}
diff --git a/TextLocator/SingleInstance/SingleInstance.cs b/TextLocator/SingleInstance/SingleInstance.cs
new file mode 100644
index 0000000000000000000000000000000000000000..5648337a3d84868ce1726a5f6e042012491bb99c
--- /dev/null
+++ b/TextLocator/SingleInstance/SingleInstance.cs
@@ -0,0 +1,301 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.Remoting;
+using System.Runtime.Remoting.Channels;
+using System.Runtime.Remoting.Channels.Ipc;
+using System.Runtime.Serialization.Formatters;
+using System.Threading;
+using System.Windows;
+using System.Windows.Threading;
+
+namespace TextLocator.SingleInstance
+{
+
+ ///
+ /// This class checks to make sure that only one instance of
+ /// this application is running at a time.
+ ///
+ ///
+ /// Note: this class should be used with some caution, because it does no
+ /// security checking. For example, if one instance of an app that uses this class
+ /// is running as Administrator, any other instance, even if it is not
+ /// running as Administrator, can activate it with command line arguments.
+ /// For most apps, this will not be much of an issue.
+ ///
+ public static class SingleInstance
+ where TApplication : Application, ISingleInstanceApp
+ {
+ #region Private Fields
+
+ ///
+ /// String delimiter used in channel names.
+ ///
+ private const string Delimiter = ":";
+
+ ///
+ /// Suffix to the channel name.
+ ///
+ private const string ChannelNameSuffix = "SingeInstanceIPCChannel";
+
+ ///
+ /// Remote service name.
+ ///
+ private const string RemoteServiceName = "SingleInstanceApplicationService";
+
+ ///
+ /// IPC protocol used (string).
+ ///
+ private const string IpcProtocol = "ipc://";
+
+ ///
+ /// Application mutex.
+ ///
+ private static Mutex singleInstanceMutex;
+
+ ///
+ /// IPC channel for communications.
+ ///
+ private static IpcServerChannel channel;
+
+ ///
+ /// List of command line arguments for the application.
+ ///
+ private static IList commandLineArgs;
+
+ #endregion
+
+ #region Public Properties
+
+ ///
+ /// Gets list of command line arguments for the application.
+ ///
+ public static IList CommandLineArgs
+ {
+ get { return commandLineArgs; }
+ }
+
+ #endregion
+
+ #region Public Methods
+
+ ///
+ /// Checks if the instance of the application attempting to start is the first instance.
+ /// If not, activates the first instance.
+ ///
+ /// True if this is the first instance of the application.
+ public static bool InitializeAsFirstInstance(string uniqueName)
+ {
+ commandLineArgs = GetCommandLineArgs(uniqueName);
+
+ // Build unique application Id and the IPC channel name.
+ string applicationIdentifier = uniqueName + Environment.UserName;
+
+ string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix);
+
+ // Create mutex based on unique application Id to check if this is the first instance of the application.
+ bool firstInstance;
+ singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance);
+ if (firstInstance)
+ {
+ CreateRemoteService(channelName);
+ }
+ else
+ {
+ SignalFirstInstance(channelName, commandLineArgs);
+ }
+
+ return firstInstance;
+ }
+
+ ///
+ /// Cleans up single-instance code, clearing shared resources, mutexes, etc.
+ ///
+ public static void Cleanup()
+ {
+ if (singleInstanceMutex != null)
+ {
+ singleInstanceMutex.Close();
+ singleInstanceMutex = null;
+ }
+
+ if (channel != null)
+ {
+ ChannelServices.UnregisterChannel(channel);
+ channel = null;
+ }
+ }
+
+ #endregion
+
+ #region Private Methods
+
+ ///
+ /// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved.
+ ///
+ /// List of command line arg strings.
+ private static IList GetCommandLineArgs(string uniqueApplicationName)
+ {
+ string[] args = null;
+ if (AppDomain.CurrentDomain.ActivationContext == null)
+ {
+ // The application was not clickonce deployed, get args from standard API's
+ args = Environment.GetCommandLineArgs();
+ }
+ else
+ {
+ // The application was clickonce deployed
+ // Clickonce deployed apps cannot recieve traditional commandline arguments
+ // As a workaround commandline arguments can be written to a shared location before
+ // the app is launched and the app can obtain its commandline arguments from the
+ // shared location
+ string appFolderPath = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);
+
+ string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
+ if (File.Exists(cmdLinePath))
+ {
+ try
+ {
+ using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode))
+ {
+ args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
+ }
+
+ File.Delete(cmdLinePath);
+ }
+ catch (IOException)
+ {
+ }
+ }
+ }
+
+ if (args == null)
+ {
+ args = new string[] { };
+ }
+
+ return new List(args);
+ }
+
+ ///
+ /// Creates a remote service for communication.
+ ///
+ /// Application's IPC channel name.
+ private static void CreateRemoteService(string channelName)
+ {
+ BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
+ serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
+ IDictionary props = new Dictionary();
+
+ props["name"] = channelName;
+ props["portName"] = channelName;
+ props["exclusiveAddressUse"] = "false";
+
+ // Create the IPC Server channel with the channel properties
+ channel = new IpcServerChannel(props, serverProvider);
+
+ // Register the channel with the channel services
+ ChannelServices.RegisterChannel(channel, true);
+
+ // Expose the remote service with the REMOTE_SERVICE_NAME
+ IPCRemoteService remoteService = new IPCRemoteService();
+ RemotingServices.Marshal(remoteService, RemoteServiceName);
+ }
+
+ ///
+ /// Creates a client channel and obtains a reference to the remoting service exposed by the server -
+ /// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service
+ /// class to pass on command line arguments from the second instance to the first and cause it to activate itself.
+ ///
+ /// Application's IPC channel name.
+ ///
+ /// Command line arguments for the second instance, passed to the first instance to take appropriate action.
+ ///
+ private static void SignalFirstInstance(string channelName, IList args)
+ {
+ IpcClientChannel secondInstanceChannel = new IpcClientChannel();
+ ChannelServices.RegisterChannel(secondInstanceChannel, true);
+
+ string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName;
+
+ // Obtain a reference to the remoting service exposed by the server i.e the first instance of the application
+ IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl);
+
+ // Check that the remote service exists, in some cases the first instance may not yet have created one, in which case
+ // the second instance should just exit
+ if (firstInstanceRemoteServiceReference != null)
+ {
+ // Invoke a method of the remote service exposed by the first instance passing on the command line
+ // arguments and causing the first instance to activate itself
+ firstInstanceRemoteServiceReference.InvokeFirstInstance(args);
+ }
+ }
+
+ ///
+ /// Callback for activating first instance of the application.
+ ///
+ /// Callback argument.
+ /// Always null.
+ private static object ActivateFirstInstanceCallback(object arg)
+ {
+ // Get command line args to be passed to first instance
+ IList args = arg as IList;
+ ActivateFirstInstance(args);
+ return null;
+ }
+
+ ///
+ /// Activates the first instance of the application with arguments from a second instance.
+ ///
+ /// List of arguments to supply the first instance of the application.
+ private static void ActivateFirstInstance(IList args)
+ {
+ // Set main window state and process command line args
+ if (Application.Current == null)
+ {
+ return;
+ }
+
+ ((TApplication)Application.Current).SignalExternalCommandLineArgs(args);
+ }
+
+ #endregion
+
+ #region Private Classes
+
+ ///
+ /// Remoting service class which is exposed by the server i.e the first instance and called by the second instance
+ /// to pass on the command line arguments to the first instance and cause it to activate itself.
+ ///
+ private class IPCRemoteService : MarshalByRefObject
+ {
+ ///
+ /// Activates the first instance of the application.
+ ///
+ /// List of arguments to pass to the first instance.
+ public void InvokeFirstInstance(IList args)
+ {
+ if (Application.Current != null)
+ {
+ // Do an asynchronous call to ActivateFirstInstance function
+ Application.Current.Dispatcher.BeginInvoke(
+ DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance.ActivateFirstInstanceCallback), args);
+ }
+ }
+
+ ///
+ /// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class
+ /// to ensure that lease never expires.
+ ///
+ /// Always null.
+ public override object InitializeLifetimeService()
+ {
+ return null;
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/TextLocator/SingleInstance/VM.cs b/TextLocator/SingleInstance/VM.cs
new file mode 100644
index 0000000000000000000000000000000000000000..b0dd6da7a54821ba25d2c11a43cf5cdfb0f64aca
--- /dev/null
+++ b/TextLocator/SingleInstance/VM.cs
@@ -0,0 +1,119 @@
+namespace TextLocator.SingleInstance
+{
+ internal enum WM
+ {
+ NULL = 0x0000,
+ CREATE = 0x0001,
+ DESTROY = 0x0002,
+ MOVE = 0x0003,
+ SIZE = 0x0005,
+ ACTIVATE = 0x0006,
+ SETFOCUS = 0x0007,
+ KILLFOCUS = 0x0008,
+ ENABLE = 0x000A,
+ SETREDRAW = 0x000B,
+ SETTEXT = 0x000C,
+ GETTEXT = 0x000D,
+ GETTEXTLENGTH = 0x000E,
+ PAINT = 0x000F,
+ CLOSE = 0x0010,
+ QUERYENDSESSION = 0x0011,
+ QUIT = 0x0012,
+ QUERYOPEN = 0x0013,
+ ERASEBKGND = 0x0014,
+ SYSCOLORCHANGE = 0x0015,
+ SHOWWINDOW = 0x0018,
+ ACTIVATEAPP = 0x001C,
+ SETCURSOR = 0x0020,
+ MOUSEACTIVATE = 0x0021,
+ CHILDACTIVATE = 0x0022,
+ QUEUESYNC = 0x0023,
+ GETMINMAXINFO = 0x0024,
+
+ WINDOWPOSCHANGING = 0x0046,
+ WINDOWPOSCHANGED = 0x0047,
+
+ CONTEXTMENU = 0x007B,
+ STYLECHANGING = 0x007C,
+ STYLECHANGED = 0x007D,
+ DISPLAYCHANGE = 0x007E,
+ GETICON = 0x007F,
+ SETICON = 0x0080,
+ NCCREATE = 0x0081,
+ NCDESTROY = 0x0082,
+ NCCALCSIZE = 0x0083,
+ NCHITTEST = 0x0084,
+ NCPAINT = 0x0085,
+ NCACTIVATE = 0x0086,
+ GETDLGCODE = 0x0087,
+ SYNCPAINT = 0x0088,
+ NCMOUSEMOVE = 0x00A0,
+ NCLBUTTONDOWN = 0x00A1,
+ NCLBUTTONUP = 0x00A2,
+ NCLBUTTONDBLCLK = 0x00A3,
+ NCRBUTTONDOWN = 0x00A4,
+ NCRBUTTONUP = 0x00A5,
+ NCRBUTTONDBLCLK = 0x00A6,
+ NCMBUTTONDOWN = 0x00A7,
+ NCMBUTTONUP = 0x00A8,
+ NCMBUTTONDBLCLK = 0x00A9,
+
+ SYSKEYDOWN = 0x0104,
+ SYSKEYUP = 0x0105,
+ SYSCHAR = 0x0106,
+ SYSDEADCHAR = 0x0107,
+ COMMAND = 0x0111,
+ SYSCOMMAND = 0x0112,
+
+ MOUSEMOVE = 0x0200,
+ LBUTTONDOWN = 0x0201,
+ LBUTTONUP = 0x0202,
+ LBUTTONDBLCLK = 0x0203,
+ RBUTTONDOWN = 0x0204,
+ RBUTTONUP = 0x0205,
+ RBUTTONDBLCLK = 0x0206,
+ MBUTTONDOWN = 0x0207,
+ MBUTTONUP = 0x0208,
+ MBUTTONDBLCLK = 0x0209,
+ MOUSEWHEEL = 0x020A,
+ XBUTTONDOWN = 0x020B,
+ XBUTTONUP = 0x020C,
+ XBUTTONDBLCLK = 0x020D,
+ MOUSEHWHEEL = 0x020E,
+
+
+ CAPTURECHANGED = 0x0215,
+
+ ENTERSIZEMOVE = 0x0231,
+ EXITSIZEMOVE = 0x0232,
+
+ IME_SETCONTEXT = 0x0281,
+ IME_NOTIFY = 0x0282,
+ IME_CONTROL = 0x0283,
+ IME_COMPOSITIONFULL = 0x0284,
+ IME_SELECT = 0x0285,
+ IME_CHAR = 0x0286,
+ IME_REQUEST = 0x0288,
+ IME_KEYDOWN = 0x0290,
+ IME_KEYUP = 0x0291,
+
+ NCMOUSELEAVE = 0x02A2,
+
+ DWMCOMPOSITIONCHANGED = 0x031E,
+ DWMNCRENDERINGCHANGED = 0x031F,
+ DWMCOLORIZATIONCOLORCHANGED = 0x0320,
+ DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
+
+ #region Windows 7
+ DWMSENDICONICTHUMBNAIL = 0x0323,
+ DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
+ #endregion
+
+ USER = 0x0400,
+
+ // This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
+ // It's relatively safe to reuse.
+ TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
+ APP = 0x8000,
+ }
+}
diff --git a/TextLocator/TextLocator.csproj b/TextLocator/TextLocator.csproj
index d9057dd033e55fb624d3e6efe274bf0e484d7280..1c4e94bdd8e9282a1cfa0e2ff0e6455557535df7 100644
--- a/TextLocator/TextLocator.csproj
+++ b/TextLocator/TextLocator.csproj
@@ -235,6 +235,7 @@
..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll
+
@@ -266,10 +267,10 @@
-
+
MSBuild:Compile
Designer
-
+
AreaEditWindow.xaml
@@ -281,6 +282,9 @@
+
+
+
@@ -337,6 +341,7 @@
+
diff --git a/TextLocator/Util/FileContentUtil.cs b/TextLocator/Util/FileContentUtil.cs
index e0f868ac3c866a5916c5b5bf8031ec83cbebdde5..f9ff71f92ca143b42e7de8134792945cbdc427c9 100644
--- a/TextLocator/Util/FileContentUtil.cs
+++ b/TextLocator/Util/FileContentUtil.cs
@@ -11,7 +11,6 @@ namespace TextLocator.Util
{
public class FileContentUtil
{
- #region RichText操作
///
/// 清空RichText的Document
///
@@ -126,6 +125,111 @@ namespace TextLocator.Util
return tpEnd.GetNextContextPosition(LogicalDirection.Forward);
}
- #endregion
+
+ ///
+ /// 获取命中摘要列表
+ ///
+ /// 内容文本
+ /// 关键词列表
+ /// 高亮色
+ /// 是否高亮背景
+ /// 切割长度
+ ///
+ public static FlowDocument GetHitBreviaryFlowDocument(string content, List keywords, System.Windows.Media.Color color, bool isBackground = false, int cutLength = int.MinValue)
+ {
+ // 定义接收命中内容上下文的列表
+ FlowDocument document = new FlowDocument();
+ if (string.IsNullOrEmpty(content))
+ {
+ return document;
+ }
+ // 如果默认值,就使用参数定义值
+ if (cutLength == int.MinValue)
+ {
+ cutLength = AppConst.FILE_CONTENT_BREVIARY_CUT_LENGTH;
+ }
+
+ // 内容(替换页码分隔符)
+ content = AppConst.REGEX_CONTENT_PAGE.Replace(content, "");
+ // 替换多余的换行
+ content = AppConst.REGEX_LINE_BREAKS_WHITESPACE.Replace(content, " ");
+ // 定义最大值和最小值、截取长度
+ int min = 0;
+ int max = content.Length;
+ // 命中数索引下标
+ int page = 1;
+ // 遍历关键词列表
+ foreach (string keyword in keywords)
+ {
+ // 定义关键词正则
+ Regex regex = new Regex(keyword, RegexOptions.IgnoreCase);
+ // 匹配集合
+ MatchCollection collection = regex.Matches(content);
+ // 遍历命中列表
+ foreach (Match match in collection)
+ {
+ // 匹配位置
+ int index = match.Index;
+
+ int startIndex = index - cutLength / 2;
+ int endIndex = index + match.Length + cutLength / 2;
+
+ // 顺序不能乱
+ if (startIndex < min) startIndex = min;
+ if (endIndex > max) endIndex = max;
+ if (startIndex > endIndex) startIndex = endIndex - cutLength;
+ if (startIndex < min) startIndex = min;
+ if (startIndex + endIndex < cutLength) endIndex = endIndex + cutLength - (startIndex + endIndex);
+ if (endIndex > max) endIndex = max;
+
+ // 开始位置
+ string before = content.Substring(startIndex, index - startIndex);
+ if (startIndex > min)
+ {
+ before = "..." + before;
+ }
+ // 关键词位置(高亮处理)
+ string highlight = content.Substring(index, match.Length);
+ // 结束位置
+ string after = content.Substring(index + match.Length, endIndex - (index + match.Length));
+ if (endIndex < max)
+ {
+ after = after + "...";
+ }
+
+ Paragraph paragraph = new Paragraph();
+ paragraph.FontSize = 13;
+ paragraph.FontFamily = new System.Windows.Media.FontFamily("微软雅黑");
+
+ Run beforeRun = new Run(before);
+ paragraph.Inlines.Add(beforeRun);
+
+ Run highlightRun = new Run(highlight);
+ highlightRun.FontWeight = FontWeight.FromOpenTypeWeight(700);
+ if (isBackground)
+ {
+ highlightRun.Background = new SolidColorBrush(color);
+ highlightRun.Foreground = new SolidColorBrush(Colors.White);
+ }
+ else
+ {
+ highlightRun.Foreground = new SolidColorBrush(color);
+ }
+
+ paragraph.Inlines.Add(highlightRun);
+
+ Run afterRun = new Run(after);
+ paragraph.Inlines.Add(afterRun);
+
+ // 分割线
+ Run pageRun = new Run(string.Format("\n------------------------------------------------------------------------------ {0}\n", page));
+ paragraph.Inlines.Add(pageRun);
+ document.Blocks.Add(paragraph);
+
+ page++;
+ }
+ }
+ return document;
+ }
}
}