i need to open a word document in a panel control of Windows Forms Application to view/edit file and save.
i use this statement :
[DllImport("user32.dll")]
public static extern int FindWindow(string strclassName, string strWindowName);
[DllImport("user32.dll")]
static extern int SetParent(int hWndChild, int hWndNewParent);
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
static extern bool SetWindowPos(
int hWnd, // handle to window
int hWndInsertAfter, // placement-order handle
int X, // horizontal position
int Y, // vertical position
int cx, // width
int cy, // height
uint uFlags // window-positioning options
);
[DllImport("user32.dll", EntryPoint = "MoveWindow")]
static extern bool MoveWindow(
int hWnd,
int X,
int Y,
int nWidth,
int nHeight,
bool bRepaint
);
const int SWP_DRAWFRAME = 0x20;
const int SWP_NOMOVE = 0x2;
const int SWP_NOSIZE = 0x1;
const int SWP_NOZORDER = 0x4;
const int SWP_FRAMECHANGED = 0x20;
ToolsComponents.MSWord word = new ToolsComponents.MSWord();
private void toolStripButton2_Click(object sender, EventArgs e)
{
word.CreateWordDocument();
word.OpenFile(@"C:UsersMEDocumentstest.docx", true);
int wordWnd = FindWindow("Opusapp", null);
if (wordWnd != 0)
{
int ret = SetParent(wordWnd, pnlShowForm.Handle.ToInt32());
//int ret2 = FindWindow("Opusapp", null);
//ret = SetParent(wordWnd, pnlShowForm.Handle.ToInt32());
SetWindowPos(wordWnd, pnlShowForm.Handle.ToInt32(), 0, 0, pnlShowForm.Bounds.Width - 20, pnlShowForm.Bounds.Height - 20, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME);
MoveWindow(wordWnd, -5, -33, pnlShowForm.Bounds.Width + 10, pnlShowForm.Bounds.Height + 57, true);
}
}
private void frmDocumentManager_FormClosing(object sender, FormClosingEventArgs e)
{
if (word != null)
{
word.CloseDoc(true);
word.Quit();
}
but this is not a good solution and have problem in runtime.
in sometimes MS word and document started outside the form and i can’t control this.
23.07.08 — 13:27
Требуется возможность просмотра (а еще лучше редактирования) вордовых доков на форме 1С, чтобы рядом были еще какие-то контролы.
Ворд прямо на форму не встроить, это факт, его можно поместить в ПТД, но и тут какая-то засада — какой-то он там не понятный, ент например свойства Documents, не понятно, как там открыть какой-либо вордовый файл.. и если в режим конфигуратора еще можно «провалитьс» в объект и даже меню в иконками вордовое появляется, то в режиме предприятия после «проваливания» сразу выкидывает обратно и ничего..
Есть ли тут люди, кто реально этим заморачивался? Открывать ворд в отдельном полноценном окне не предлагать.
1 — 23.07.08 — 13:36
а назачем? а вообще — в 7-ке было так: вставляешь активикс куда тебе надо, и делаешь с ним дальше все, что хочешь (и не только ворд, а все, что хочешь)…
2 — 23.07.08 — 13:38
нужно видеть одновременно ворд и другую инфу, при этом еще и редактировать желательно и то и другое..
3 — 23.07.08 — 13:40
(2) дык и? экран маленький?
4 — 23.07.08 — 13:41
(3) в смысле, чем ворд в отдельном окне не устраивает?
5 — 23.07.08 — 13:45
Через поле HTML документа можно сделать
6 — 23.07.08 — 13:51
(4) нужно на одной форме
(5) думал уже об этом, но тут другая засада — печататься должно 1в1 как в ворде, а при конвертации в html перекосы неизбежны
7 — 23.07.08 — 13:54
(6) Так и печатй средствами Word. Используй COM-объект для этого.
8 — 23.07.08 — 13:55
Word = ПолучитьCOMОбъект(ПолноеИмяФайла);
Word.PrintOut();
9 — 23.07.08 — 13:58
(8) это понятно, но все-равно спасибо
это вариант в readonly, есть же какие-то варианты с возможнорстью редактировани на одной форме?
Ворд = ЭлементыФормы.ПолеТабличногоДокумента1.Рисунки.Ворд.Объект;
Ворд.Application.Documents.Open(ФайлЗагрузки);
в итоге файл открывается «в тени», и не отображается на встроенном в ПТД объекте.. может я что-то делаю не так?
10 — 23.07.08 — 13:59
форма-вставитьактивикс… должен быть в спиське ворд (если на компе есть) у меня нету — так что помочь дальше не смогу…
11 — 23.07.08 — 14:00
(10)+ а счас терминал туда прикрутил… забавно, 1с в терминале, который открыт в 1с
12 — 23.07.08 — 14:01
ЭлементыФормы.HTMLОкно.Перейти(ПолноеИмяФайла);
и правь сколько угодно. И печатай кстати тоже
13 — 23.07.08 — 14:02
Кидай на форму поле HTML документа, в него загружай вордовский файл и радуйся
14 — 23.07.08 — 14:02
15 — 23.07.08 — 14:17
(9) мыло дай отправлю заготовку
16 — 23.07.08 — 14:54
(10) его там и не будет, в 1С ворд можно вставить только на ПТД
(15) main8 mailru
17 — 23.07.08 — 14:55
(14) это совсем другое
18 — 23.07.08 — 15:00
попробовал через html, уже лучше.. осталось выяснить, как отключить запрос на «открыть или сохранить» и вывести все необходимые иконки, а то по-умолчанию виден только блок «рецензирование»
19 — 23.07.08 — 15:08
и еще теперь не понятно, как отловить ком объект, чтобы навесить событие на сохранение ворда
20 — 23.07.08 — 15:32
(19) Отправил
21 — 24.07.08 — 12:18
Подниму тему. Остался не решенным вопрос следующий:
Когда мы выводим вордовый документ в ПолеHTMLДокумента, есть ли какая-то возможность управлять этим объектом ворд? например, хотя бы сделать
CommandBars(«Standard»).Visible = True
все же похоже открывая в ПолеHTMLДокумента мы действительно просто открываем документ, а не встраиваем объект, но сам то объект ворд в памяти создается. можно к нему как-то обратиться?
PrizrakR
22 — 24.07.08 — 15:12
скорее для истории:
(12) в ХР/офисе 2003 это прокатывает, а вот в висте/2007 ворд всегда открывается в новом своем окне (возможно конечно надо где-то реестр виндовый поправить, но вот где и не факт что так), так что остается вариант принудительной конвертации doc -> html и уже его выводить
Всем доброго времени суток, господа программисты!
Заранее прошу всех: слабонервных, раздраженных, злых, недовольных и прочих — ИДТИ МИМО! Давайте не будем портить настроение друг другу .
Я никого не заставляю мне отвечать.
Теперь, перейдем к делу.
У меня появилась проблемка с ресурсами проекта.
Нужно: включить офисный doc файл в проект, потом открыть его, сделать изменения и показать его пользователю, чтобы он дальше решил что с ним делать.
То есть, у меня есть word файл (например) с таблицей, в которой хранятся данные. Мне нужно чтобы этот файл хранился постоянно в моем проекте и открывался/редактировался при нажатии кнопки на форме.
И самое главное — все это должно компилироваться в один exe файл.
Как это сделать?
P.s.: я начинающий, поэтому «пинать не надо»!
Добавлено через 12 минут
Кстати, щас читаю темку «Бинарная сериализация». Пытаюсь разобраться, но пока безуспешно.
I’m trying to make my program have the ability to display a Microsoft Word file on a form but not having any luck in doing so. I want to be able to open the file and display it on the form as a Read-Only. So basically just display it’s contents. Various users on the web have recommended displaying files in the WebBrowser control (under toolbox). I have tried this but failed to get it working. My end goal is to be able to annotate on top of the web browser (or something of similar manner) and subsequently save the annotations along with the opened file.
I’m not that experienced in the C# language too so any help on how to achieve my problem would be greatly appreciated.
user513951
12.2k7 gold badges67 silver badges81 bronze badges
asked Feb 14, 2015 at 22:39
4
You need a DOCX viewer control. My company recently gave away our multi-format WinForms viewer control as a free product — XtremeDocumentStudio .NET Free. It can display DOCX and is available on NuGet. It does not require a Web Browser control for embedding an online viewer or Word software installed locally.
http://www.nuget.org/packages/XtremeDocumentStudio.NETFree/
answered Feb 16, 2015 at 5:23
gn1gn1
5302 silver badges5 bronze badges
9
There are some good links that might help you.
First, you will find a closely related or similar question here
And in that conversation someone posted the following link which is about how to build a user control for displaying Word documents in a webbrowser control.
I also found another article here about how to integrate Excel in a Windows Form application using WebBrowser. But Excel is used as an example and you may be able to adapt it to Word.
answered Feb 14, 2015 at 23:56
alainlompoalainlompo
4,4044 gold badges34 silver badges41 bronze badges
2
- Remove From My Forums
-
Question
-
Hi i want to open an existing word document in my windows form application! i want to open it by clicking from a menu item!!! it is to open the user documentation of the application!! i tried using most of the codes but none of them gave me successful results
this is the code i used:
this.Application.Documents.Open(@"D:HD ProjectUser Documentation.docx");
and i used the following header for this
using Microsoft.Office.Interop.Word;this is another code
Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
wdApp.Visible = true;
Word.Document aDoc = wdApp.Documents.Open(@"D:HD ProjectUser Documentation.docx");Can some one please tell me what the problem is??
thanks in advance-
Moved by
Thursday, November 17, 2011 2:29 PM
Not IDE related (From:Visual C# IDE)
-
Moved by
Answers
-
Declaring the namespace as you did, ‘using Microsoft.Office.Interop.Word;’, is fine. If you do this:
Word.Document aDoc
should be
Document aDoc
You can also declare your variables the long way, which will work even if you do not declare the namespace. You have done this for your word application (Microsoft.Office.Interop.Word.Application wdApp). You could also do this for the document (Microsoft.Office.Interop.Word.Document
aDoc)Also, There is clearly some problem with the references. You have a duplicate; two referrences point to instances of the Word Object Library. In the solution explorer, expand the ‘references’ section, and then delete one. If you right click each and look
at the properties, you can see the library file they point to.-
Edited by
JosephFox
Friday, November 18, 2011 10:30 AM -
Marked as answer by
Mirfath_
Friday, November 18, 2011 11:15 AM
-
Edited by