saikat banik

saikat banik

  • NA
  • 36
  • 1.9k

How to send Keypress events in MS word Application

Sep 15 2020 7:43 AM
Hi every one I am new in C# . I am facing some problem that's I want to send a keypress event (ALT+J+P+Q+S) to MS Word Application docx file .  Here is my code I am extracting the images from docx files then I want to send keypress event (ALT+J+P+Q+S) for each Image where in this code function name SaveInlineShapeToFile() under this function inlineShape.Select();  - is selecting each image in MSWordApplication docx file after that I want to send keypress (ALT+J+P+Q+S) that will execute in MS Word Application . Please help me to solve this problem . 
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Activities;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using Application = Microsoft.Office.Interop.Word.Application;
namespace MSWordExtract
{
public class SaveWordImage : CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
var wordApplication = new Application();
var document = wordApplication.Documents.Open(@"D:\C#\Project.docx");
for (var i = 1; i <= wordApplication.ActiveDocument.InlineShapes.Count; i++)
{
var inlineShapeId = i;
var thread = new Thread(() => SaveInlineShapeToFile(inlineShapeId, wordApplication,context));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
wordApplication.Quit();
Console.ReadLine();
}
 
protected void SaveInlineShapeToFile(int inlineShapeId, Application wordApplication, CodeActivityContext context)
{
var inlineShape = wordApplication.ActiveDocument.InlineShapes[inlineShapeId];
inlineShape.Select();
 
///SendKeys.SendWait("%{JPQS}");
 
 
wordApplication.Selection.Copy();
// Check data is in the clipboard
if (Clipboard.GetDataObject() != null)
{
var data = Clipboard.GetDataObject();
// Check if the data conforms to a bitmap format
if (data != null && data.GetDataPresent(DataFormats.Bitmap))
{
// Fetch the image and convert it to a Bitmap
var image = (Image)data.GetData(DataFormats.Bitmap, true);
var currentBitmap = new Bitmap(image);
// Save the bitmap to a file
currentBitmap.Save(@"D:\C#\Image_Test" + String.Format("img_{0}.png", inlineShapeId));
}
}
}
}
}

Answers (3)