去年接了个没给钱的私活,就是做这么一个东西,最后也没着落了,今天就把代码发出来大家分享下。

为了,凑字数,直接贴代码:

ppt2image
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Configuration;
  4 using System.Drawing;
  5 using System.Drawing.Imaging;
  6 using System.Linq;
  7 using System.Runtime.InteropServices;
  8 using System.Text;
  9 using System.Threading;
 10 using Microsoft.Office.Core;
 11 using PowerPoint = Microsoft.Office.Interop.PowerPoint;
 12 using System.Diagnostics;
 13 using ThreadState = System.Threading.ThreadState;
 14 using System.IO;
 15 
 16 namespace PPT2Image
 17 {
 18     static class Program
 19     {
 20         [DllImport("Gdi32.dll")]
 21         private static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
 22 
 23         private static Object obj = new object();
 24         /// <summary>
 25         /// 图片集合
 26         /// </summary>
 27         private static Queue<Bitmap> _imageList = new Queue<Bitmap>();
 28         /// <summary>
 29         /// 索引表
 30         /// </summary>
 31         private static Dictionary<Int32, IndexObject> _indexs = new Dictionary<Int32, IndexObject>();
 32         /// <summary>
 33         /// 每页等待时间
 34         /// </summary>
 35         private static Int32 deplyTime = 3000;
 36 
 37         private static PowerPoint.Application _objApp;
 38         private static PowerPoint._Presentation _objPres;
 39 
 40         private static Int32 width = Int32.Parse(ConfigurationManager.AppSettings["width"]);
 41         private static Int32 height = Int32.Parse(ConfigurationManager.AppSettings["height"]);
 42 
 43         /// <summary>
 44         /// 图片全局索引
 45         /// </summary>
 46         private static Int32 _index = 1;
 47         /// <summary>
 48         /// 图片前一个全局索引
 49         /// </summary>
 50         private static Int32 _prev_index = 1;
 51 
 52         // 图片的流水号
 53         private static Int32 _view_index = 1;
 54         // 图片对应的PPT页面编号
 55         private static Int32 _slide_index = -1;
 56         // 图片对应的前一个PPT页面编号
 57         private static Int32 _prev_slide_index = 1;
 58 
 59         /// <summary>
 60         /// 每秒图片张数
 61         /// </summary>
 62         //private static Int32 ImageNum = 20;
 63 
 64         private static String _noteFilePath;
 65         private static String _resultFilePath;
 66         private static String _outputPath;
 67         private static String _filePath;
 68 
 69         /// <summary>
 70         /// 索引对象
 71         /// </summary>
 72         private class IndexObject
 73         {
 74             /// <summary>
 75             /// PPT页索引
 76             /// </summary>
 77             public Int32 SlideIndex { get; set; }
 78             /// <summary>
 79             /// PPT页动画索引
 80             /// </summary>
 81             public Int32 ViewIndex { get; set; }
 82         }
 83 
 84         private static Int32 PixelsToPoints(Int32 val, Boolean vert)
 85         {
 86             Double result;
 87             if (vert)
 88             {
 89                 result = Math.Truncate(val * 0.75);
 90             }
 91             else
 92             {
 93                 result = Math.Truncate(val * 0.75);
 94             }
 95 
 96             return (Int32)result;
 97         }
 98 
 99         static void Main(string[] args)
100         {
101             ParseArgs(args);
102 
103             var fileName = Path.GetFileNameWithoutExtension(_filePath);
104 
105             _noteFilePath = Path.Combine(_outputPath, fileName + "_note.txt");
106             _resultFilePath = Path.Combine(_outputPath, fileName + "_result.txt");
107 
108             if (!Directory.Exists(Path.Combine(_outputPath, "images")))
109             {
110                 Directory.CreateDirectory(Path.Combine(_outputPath, "images"));
111             }
112 
113             var imgsPath = Path.Combine(_outputPath, "images.jpg");
114             try
115             {
116                 _objApp = new PowerPoint.Application();
117                 _objPres = _objApp.Presentations.Open(_filePath, WithWindow: MsoTriState.msoFalse);
118 
119                 _objPres.SaveAs(imgsPath, PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
120 
121 
122                 // 保存备注
123                 SaveNoteInfo();
124 
125                 // 设置呈现窗口
126                 SetSildeShowWindow();
127 
128                 var pptRenderThread = InitPPTRenderThread();
129                 var imageSaveThread = InitImageSaveThread();
130 
131                 pptRenderThread.Start();
132                 imageSaveThread.Start();
133 
134                 while (_objApp.SlideShowWindows.Count >= 1) Thread.Sleep(deplyTime / 10);
135 
136                 pptRenderThread.Abort();
137                 //pptRenderThread.Join();
138                 imageSaveThread.Abort();
139                 //imageSaveThread.Join();
140 
141                 _objPres.Save();
142 
143                 _objApp.Quit();
144             }
145             catch (Exception ex)
146             {
147                 Console.WriteLine(ex.Message);
148             }
149 
150             // 杀死powerpnt
151             KillProcess("powerpnt");
152 
153             SaveResult();
154 
155             // 退出
156             Environment.Exit(0);
157         }
158 
159         /// <summary>
160         /// 杀死进程
161         /// </summary>
162         /// <param name="processName"></param>
163         private static void KillProcess(String processName)
164         {
165             foreach (var process in Process.GetProcesses())
166             {
167                 if (process.ProcessName.ToLower().Contains(processName))
168                 {
169                     process.Kill();
170                 }
171             }
172         }
173 
174         /// <summary>
175         /// 初始化参数
176         /// </summary>
177         private static void ParseArgs(String[] args)
178         {
179             // 文件路径
180             _filePath = args[1];
181             // 输出路径
182             _outputPath = args[3];
183         }
184 
185         /// <summary>
186         /// 保存结果
187         /// </summary>
188         private static void SaveResult()
189         {
190             var stream = new FileStream(_resultFilePath, FileMode.Create);
191             var writer = new StreamWriter(stream);
192 
193             var prevSlideIndex = 0;
194 
195             // key是图片节点信息
196             foreach (var key in _indexs.Keys)
197             {
198                 if (_indexs[key].SlideIndex != prevSlideIndex)
199                 {
200                     // 前一个key与后一个key之间的图片为一组
201                     writer.WriteLine(_indexs[key].SlideIndex + "-" + _indexs[key].ViewIndex);
202                 }
203                 else
204                 {
205                     // 前一个key与后一个key之间的图片为一组
206                     writer.WriteLine(_indexs[key].SlideIndex + "-" + _indexs[key].ViewIndex);
207                 }
208 
209                 writer.Flush();
210                 stream.Flush();
211             }
212 
213             writer.Close();
214             stream.Close();
215 
216             writer.Dispose();
217             stream.Dispose();
218         }
219 
220         /// <summary>
221         /// 初始化图片保存线程
222         /// </summary>
223         /// <returns></returns>
224         private static Thread InitImageSaveThread()
225         {
226             var imageIndex = 1;
227             var imageSaveThread = new Thread(() =>
228                 {
229                     while (true)
230                     {
231                         if (_imageList.Count == 0) continue;
232                         lock (obj)
233                         {
234                             var bmp = _imageList.Dequeue();
235                             using (var stream = new FileStream(Path.Combine(_outputPath, imageIndex.ToString("0000") + ".jpg"), FileMode.Create))
236                             {
237                                 bmp.Save(stream, ImageFormat.Jpeg);
238 
239                                 bmp.Dispose();
240                             }
241 
242                             imageIndex++;
243                         }
244                     }
245                 });
246 
247             return imageSaveThread;
248         }
249 
250 
251         /// <summary>
252         /// 初始化抓图线程
253         /// </summary>
254         /// <param name="objPres"></param>
255         /// <returns></returns>
256         private static Thread InitCaptureThread(PowerPoint._Presentation objPres)
257         {
258             var thread = new Thread(() =>
259             {
260                 while (true)
261                 {
262                     try
263                     {
264                         var bmp = new Bitmap(width, height);
265                         Graphics gSrc = Graphics.FromHwnd((IntPtr)objPres.SlideShowWindow.HWND);
266                         IntPtr hdcSrc = gSrc.GetHdc();
267                         Graphics gDes = Graphics.FromImage(bmp);
268                         IntPtr hdcDes = gDes.GetHdc();
269 
270                         BitBlt(hdcDes, 0, 0, width, height, hdcSrc, 0, 0,
271                                (int)(CopyPixelOperation.SourceCopy));
272 
273                         gSrc.ReleaseHdc(hdcSrc);
274                         gDes.ReleaseHdc(hdcDes);
275                         gSrc.Dispose();
276                         gDes.Dispose();
277 
278                         _imageList.Enqueue(bmp);
279                     }
280                     catch (Exception ex)
281                     {
282                         Console.WriteLine(ex.Message);
283                     }
284 
285                     // 截取140张 退出线程
286 //                    if (_index % 140 == 0)
287 //                    {
288 //                        // 图片索引+1
289 //                        _index++;
290 //
291 //                        Thread.CurrentThread.Abort();
292 //
293 //                        return;
294 //                    }
295 
296                     // 图片索引+1
297                     _index++;
298 
299                     // 修改暂停时间
300                     Thread.Sleep(35);
301                 }
302             });
303 
304             // 设置最大优先级
305             thread.Priority = ThreadPriority.Highest;
306 
307             return thread;
308         }
309 
310         /// <summary>
311         /// 初始化PPT呈现线程
312         /// </summary>
313         /// <returns></returns>
314         private static Thread InitPPTRenderThread()
315         {
316             var pptRenderThread = new Thread(() =>
317                 {
318                     // 第一次
319                     Thread thread = InitCaptureThread(_objPres);
320 
321                     try
322                     {
323                         if (_slide_index == -1)
324                         {
325                             _slide_index = 1;
326                             _objPres.SlideShowWindow.View.First();
327                             _objPres.SlideShowWindow.View.GotoSlide(1);
328                             _objPres.SlideShowWindow.View.ResetSlideTime();
329 
330                             // 前一个全局索引等于_index
331                             _prev_index = _index;
332 
333                             _indexs.Add(_index, new IndexObject()
334                                 {
335                                     SlideIndex = _slide_index,
336                                     ViewIndex = _view_index
337                                 });
338 
339                             thread.Start();
340                         }
341                     }
342                     catch (Exception ex)
343                     {
344                         Console.WriteLine(ex.Message);
345                     }
346 
347                     while (true)
348                     {
349                         try
350                         {
351                             // 等待3秒
352                             Thread.Sleep(deplyTime);
353 
354                             //if (thread.ThreadState == ThreadState.Running
355                             //    || thread.ThreadState != ThreadState.Unstarted)
356                             //{
357                             _view_index++;
358 
359                             if (thread.ThreadState != ThreadState.Aborted)
360                             {
361                                 thread.Abort();
362                             }
363                             thread = InitCaptureThread(_objPres);
364 
365                             // 前一个全局索引等于_index
366                             _prev_index = _index;
367 
368                             // 启动之前,保存索引信息
369                             _indexs.Add(_index, new IndexObject()
370                             {
371                                 SlideIndex = _slide_index,
372                                 ViewIndex = _view_index
373                             });
374 
375                             thread.Start();
376                             //}
377 
378                             // 下一个动画页面
379                             _objPres.SlideShowWindow.View.Next();
380 
381                             if (_slide_index != -1)
382                             {
383                                 // 获取当前PPT索引,第几张PPT
384                                 _slide_index = _objPres.SlideShowWindow.View.Slide.SlideIndex;
385 
386                                 if (_prev_slide_index != _slide_index)
387                                 {
388                                     _view_index = 1;
389                                     _prev_slide_index = _slide_index;
390 
391                                     // 修改前一个全局索引对应的值
392                                     _indexs[_prev_index] = new IndexObject()
393                                         {
394                                             SlideIndex = _slide_index,
395                                             ViewIndex = _view_index
396                                         };
397                                 }
398                             }
399                         }
400                         catch (Exception ex)
401                         {
402                             Console.WriteLine(ex.Message);
403                         }
404                     }
405                 });
406 
407             pptRenderThread.Priority = ThreadPriority.Highest;
408 
409             return pptRenderThread;
410         }
411 
412         /// <summary>
413         /// 设置呈现窗口
414         /// </summary>
415         private static void SetSildeShowWindow()
416         {
417             // 起始页面索引
418             _objPres.SlideShowSettings.StartingSlide = 1;
419             // 结束页面索引
420             _objPres.SlideShowSettings.EndingSlide = _objPres.Slides.Count;
421             // 放映开始
422             _objPres.SlideShowSettings.Run();
423 
424             // 设置放映窗口宽度
425             _objPres.SlideShowWindow.Width = PixelsToPoints(width, false);
426             // 设置放映窗口高度
427             _objPres.SlideShowWindow.Height = PixelsToPoints(height, true);
428             // 设置放映窗口Top
429             _objPres.SlideShowWindow.Top = 0;
430             // 设置放映窗口Left
431             _objPres.SlideShowWindow.Left = 0;
432         }
433 
434         /// <summary>
435         /// 保存备注信息
436         /// </summary>
437         private static void SaveNoteInfo()
438         {
439             var stream = new FileStream(_noteFilePath, FileMode.Create);
440             var writer = new StreamWriter(stream);
441 
442             var note = new StringBuilder("{");
443 
444             foreach (PowerPoint.Slide slide in _objPres.Slides)
445             {
446                 //writer.Write(slide.SlideIndex + "@");
447                 //读取每个幻灯片的备注文本  
448                 note.Append("{\"page\":\"" + slide.SlideIndex + "\",");
449 
450                 foreach (PowerPoint.Shape nodeshape in slide.NotesPage.Shapes)
451                 {
452                     if (nodeshape.TextFrame.HasText.Equals(MsoTriState.msoTrue))
453                     {
454                         //备注      
455                         note.Append("\"note\":\"" + nodeshape.TextFrame.TextRange.Text + "\"");
456                         //writer.Write(nodeshape.TextFrame.TextRange.Text);
457                     }
458                 }
459 
460                 note.Append("},");
461                 //writer.WriteLine();
462             }
463 
464             note = note.Remove(note.Length - 1, 1).Append("}");
465 
466             writer.Write(note);
467 
468             writer.Close();
469             stream.Close();
470 
471             writer.Dispose();
472             stream.Dispose();
473         }
474     }
475 }
ppt2vedio
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Diagnostics;
  4 using System.IO;
  5 using System.Linq;
  6 using System.Text;
  7 using System.Text.RegularExpressions;
  8 using System.Threading;
  9 using System.Threading.Tasks;
 10 using System.Configuration;
 11 
 12 namespace PPT2Vedio
 13 {
 14     static class Program
 15     {
 16         // 处理文件夹临时路径
 17         private static String tempPath = ConfigurationManager.AppSettings["tempPath"];
 18         // 处理结果保存路径
 19         private static String resultPath = ConfigurationManager.AppSettings["resultPath"];
 20         // 视频分辨率
 21         private static String resolution = ConfigurationManager.AppSettings["resolution"];
 22 
 23         static void Main(string[] args)
 24         {
 25             // 监测文件夹路径
 26             var moniterPath = ConfigurationManager.AppSettings["moniterPath"];
 27 
 28             // 初始化文件夹监控线程
 29             var folderMoniterThread = InitFolderMoniterThread();
 30             folderMoniterThread.Start(moniterPath);
 31         }
 32 
 33         /// <summary>
 34         /// 文件夹监控线程
 35         /// </summary>
 36         private static Thread InitFolderMoniterThread()
 37         {
 38             var thread = new Thread(path =>
 39                 {
 40                     while (true)
 41                     {
 42                         // 获取监控路径中的文件数量
 43                         String[] files = Directory.GetFiles(path.ToString(), "*.ppt*");
 44 
 45                         var builder = new StringBuilder();
 46 
 47                         foreach (var file in files)
 48                         {
 49                             builder.Append(file + "  ");
 50                         }
 51 
 52                         LogFactory.Info("获取文件数量:{0}  {1}", files.Length, builder);
 53 
 54                         // 先把文件转移
 55                         foreach (var file in files)
 56                         {
 57                             var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
 58 
 59                             // 如果路径有中文,替换为guid
 60                             if (HasChinese(fileNameWithoutExtension))
 61                             {
 62                                 fileNameWithoutExtension = Guid.NewGuid().ToString().Replace("-", "");
 63                             }
 64 
 65                             var path1 = Path.Combine(tempPath, fileNameWithoutExtension);
 66 
 67                             if (!Directory.Exists(path1))
 68                             {
 69                                 Directory.CreateDirectory(path1);
 70                             }
 71 
 72                             LogFactory.Info("移动文件到新路径:{0}", path1);
 73 
 74                             var newPath = Path.Combine(path1, Path.GetFileName(file));
 75 
 76                             // 复制文件
 77                             File.Move(file, newPath);
 78 
 79                             LogFactory.Info("开始处理文件:{0}", file);
 80                             OperateFile(newPath);
 81                         }
 82 
 83                         // 3秒检查一次
 84                         Thread.Sleep(1000 * 3);
 85                     }
 86                 });
 87 
 88             return thread;
 89         }
 90 
 91         /// <summary>
 92         /// 初始化处理文件线程
 93         /// </summary>
 94         /// <returns></returns>
 95         private static void OperateFile(String path)
 96         {
 97             var rootPath = Path.GetDirectoryName(path);
 98 
 99             // 启动转换Image程序
100             CallProcess("ppt2image.exe", String.Format("-f {0} -o {1}", path, rootPath), false);
101 
102             // 杀死进程
103             KillProcess("ppt2image");
104 
105             // 生成结果文件
106             GernateResult(path);
107 
108             // 删除临时文件
109             Directory.Delete(rootPath, true);
110         }
111 
112         /// <summary>
113         /// 生成结果文件
114         /// </summary>
115         /// <param name="path"></param>
116         private static void GernateResult(String path)
117         {
118             var rootPath = Path.GetDirectoryName(path);
119 
120             var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
121 
122             if (!Directory.Exists(Path.Combine(resultPath, fileNameWithoutExtension)))
123             {
124                 Directory.CreateDirectory(Path.Combine(resultPath, fileNameWithoutExtension));
125             }
126 
127             // 复制备注结果文件
128             File.Copy(Path.Combine(rootPath, fileNameWithoutExtension + "_note.txt"),
129                       Path.Combine(resultPath, fileNameWithoutExtension, "note.txt"), true);
130 
131 
132             // 复制文件
133             File.Copy("ffmpeg.exe", Path.Combine(rootPath, "ffmpeg.exe"), true);
134 
135 
136             var resultFilePath = Path.Combine(rootPath, fileNameWithoutExtension + "_result.txt");
137 
138             var list = GetFileToList(resultFilePath);
139 
140             List<String> durations = null;
141 
142             try
143             {               
144                 // mp4临时文件
145                 var mp4TempFilePath = Path.Combine(rootPath, fileNameWithoutExtension + ".mp4");
146 
147                 // 启动转换Vedio程序
148                 var resultStr = CallProcess(Path.Combine(rootPath, "ffmpeg.exe"),
149                                             String.Format("-i \"{0}\" -r 45 -f mp4 -s {1} -b 600k -vcodec h264 {2}",
150                                                             Path.Combine(rootPath, "%04d.jpg"),
151                                                             resolution, mp4TempFilePath), true);
152 
153                 durations = GetDurations(resultStr);
154 
155                 File.Copy(mp4TempFilePath, Path.Combine(resultPath, fileNameWithoutExtension, fileNameWithoutExtension + ".mp4"), true);
156             }
157             catch (Exception ex)
158             {
159                 LogFactory.Error("生成MP4文件异常:" + ex.Message);
160             }
161 
162             // 复制图片文件
163             var files = Directory.GetFiles(Path.Combine(rootPath, "images"));
164 
165             for (int index = 0; index < files.Length; index++)
166             {
167                 try
168                 {
169                     var file = files[index];
170                     File.Move(file, Path.Combine(resultPath, fileNameWithoutExtension, (index + 1) + ".png"));
171                 }
172                 catch (Exception ex)
173                 {
174                     LogFactory.Error("复制PPT图片报错:" + ex.Message);
175                 }
176 
177             }
178             try
179             {
180                 SaveResultFile(resultFilePath, list, durations);
181 
182                 File.Copy(resultFilePath,
183                     Path.Combine(resultPath, fileNameWithoutExtension, "result.txt"), true);
184             }
185             catch (Exception ex)
186             {
187                 LogFactory.Error("复制结果文件报错:" + ex.Message);
188             }
189         }
190 
191         /// <summary>
192         /// 改变文件名称
193         /// </summary>
194         /// <param name="startIndex"></param>
195         /// <param name="endIndex"></param>
196         /// <param name="files"></param>
197         /// <param name="filePrefix"></param>
198         private static void ChangeFileName(Int32 startIndex, Int32 endIndex, String[] files, String filePrefix)
199         {
200             var tempEndIndex = startIndex + 94;
201 
202             Int32 index = 1;
203             foreach (var file in files)
204             {
205                 var fileIndex = Int32.Parse(Path.GetFileNameWithoutExtension(file));
206 
207                 if (fileIndex >= startIndex &&
208                     fileIndex <= tempEndIndex)
209                 {
210                     if (fileIndex <= endIndex)
211                     {
212                         // 如果在最后的索引范围内,直接复制
213                         File.Copy(file, Path.Combine(Path.GetDirectoryName(file), filePrefix + "-" + index.ToString("000") + ".jpg"), true);
214                     }
215                     else
216                     {
217                         // 如果超出索引,复制最后一个文件
218                         File.Copy(files[endIndex - 1], Path.Combine(Path.GetDirectoryName(file), filePrefix + "-" + index.ToString("000") + ".jpg"), true);
219                     }
220 
221 
222                     index++;
223                 }
224                 else
225                 {
226                     index = 1;
227                 }
228             }
229         }
230 
231         /// <summary>
232         /// 读取文件到集合中
233         /// </summary>
234         /// <param name="filePath"></param>
235         /// <returns></returns>
236         private static List<String> GetFileToList(String filePath)
237         {
238             var list = new List<String>();
239 
240             // 读取结果文件
241             var stream = new FileStream(filePath, FileMode.Open);
242             var reader = new StreamReader(stream);
243 
244             while (!reader.EndOfStream)
245             {
246                 list.Add(reader.ReadLine());
247             }
248 
249             reader.Close();
250             stream.Close();
251 
252             reader.Dispose();
253             stream.Dispose();
254 
255             return list;
256         }
257 
258         /// <summary>
259         /// 保存结果文件
260         /// </summary>
261         private static void SaveResultFile(String resultFilePath, IEnumerable<string> result, List<String> durations)
262         {
263             var stream = new FileStream(resultFilePath, FileMode.Create);
264             var writer = new StreamWriter(stream);
265 
266             var temp = new StringBuilder("{");
267 
268             //var length = durations.Count > result.Count + 1 ? result.Count : durations.Count - 1;
269             var duration = 3;
270             foreach (var str in result)
271             {
272                 var t = str.Split('-');
273                 var page = t[0];
274                 var animation = t[1];
275                 
276                 temp.Append("{\"page\":\"" + page + "\",\"animation\":\"" +
277                             animation + "\",\"duration\":\"" + duration + "\"},");
278 
279                 writer.Flush();
280                 stream.Flush();
281 
282                 duration += 3;
283             }
284 
285             temp = temp.Remove(temp.Length - 1, 1).Append("}");
286 
287             writer.Write(temp);
288 
289             writer.Close();
290             stream.Close();
291 
292             writer.Dispose();
293             stream.Dispose();
294         }
295 
296         /// <summary>
297         /// 保存结果文件
298         /// </summary>
299         private static List<String> GetDurations( String resultStr)
300         {
301             var reg = new Regex(@"time=(?<time>\d{2}:\d{2}:\d{2}.\d{2})");
302             var matches = reg.Matches(resultStr);
303 
304             var list = new List<String>();
305 
306             for (int i = 0; i < matches.Count; i++)
307             {
308                 Match match = matches[i];
309                 list.Add(match.Groups["time"].Value);
310             }
311 
312             var tempList = new List<String>();
313             // 合并结果
314             for (int i = 0; i < list.Count - 1; i++)
315             {
316                 var str1 = list[i];
317                 var str2 = list[i + 1];
318             }
319 
320             return list;
321         }
322 
323         /// <summary>
324         /// 判断是否有中文
325         /// </summary>
326         /// <param name="words"></param>
327         /// <returns></returns>
328         public static bool HasChinese(string words)
329         {
330             string temp;
331             for (int i = 0; i < words.Length; i++)
332             {
333                 temp = words.Substring(i, 1);
334                 byte[] sarr = Encoding.GetEncoding("gb2312").GetBytes(temp);
335                 if (sarr.Length == 2)
336                 {
337                     return true;
338                 }
339             }
340             return false;
341         }
342 
343         /// <summary>
344         /// 杀死进程
345         /// </summary>
346         /// <param name="processName"></param>
347         private static void KillProcess(String processName)
348         {
349             foreach (var process in Process.GetProcesses())
350             {
351                 if (process.ProcessName.ToLower().Contains(processName))
352                 {
353                     process.Kill();
354                 }
355             }
356         }
357 
358         /// <summary>
359         /// 启动程序
360         /// </summary>
361         /// <param name="fileName"></param>
362         /// <param name="args"></param>
363         /// <param name="isGetResults"> </param>
364         private static String CallProcess(string fileName, string args, Boolean isGetResults)
365         {
366             var process = new Process();
367             process.StartInfo.FileName = fileName;//设置运行的命令行文件
368             process.StartInfo.Arguments = args;//设置命令参数
369             process.StartInfo.CreateNoWindow = true;//不显示dos命令行窗口
370             process.StartInfo.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
371             process.StartInfo.RedirectStandardOutput = isGetResults;
372             process.StartInfo.RedirectStandardError = isGetResults;
373 
374             // 启动
375             process.Start();
376 
377             var result = new StringBuilder();
378 
379             if (isGetResults)
380             {
381                 process.OutputDataReceived += (s, e) => result.AppendLine(e.Data);
382                 process.ErrorDataReceived += (s, e) => result.AppendLine(e.Data);
383 
384                 process.BeginErrorReadLine();
385                 process.BeginOutputReadLine();
386             }
387 
388 
389             // 等待完成
390             process.WaitForExit();
391 
392             if (isGetResults)
393             {
394                 process.CancelOutputRead();
395                 process.CancelErrorRead();
396 
397                 return result.ToString();
398             }
399             else
400             {
401                 return "";
402             }
403         }
404     }
405 }

下载地址:百度网盘

posted on 2013-03-27 21:06  danny.fu  阅读(1216)  评论(8编辑  收藏  举报