[英]WPF WebBrowser control doesn't enter design mode when the document property is changed
[英]How do I detect when the content of a WebBrowser control has changed (in design mode)?
我在設計模式下使用WebBrowser
控件。
webBrowser1.DocumentText = "<html><body></body></html>";
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
我有一個保存按鈕,我想根據控件的內容是否已更改來啟用或禁用它。
我還需要知道控件的內容何時更改,因為我需要阻止用戶離開控件而不接受確認消息框,說明他們的更改將丟失。
我找不到任何讓我知道內容已更改的事件。
沒有這樣的事件,因為 DocumentText 是一個簡單的字符串。 我會創建一個字符串變量來存儲最后保存的文本,並在每個 KeyDown / MouseDown / Navigating 事件中檢查它。
string lastSaved;
private void Form_Load(object sender, System.EventArgs e)
{
// Load the form then save WebBrowser text
this.lastSaved = this.webBrowser1.DocumentText;
}
private void webBrowser1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Check if it changed
if (this.lastSaved != this.webBrowser1.DocumentText)
{
// TODO: changed, enable save button
this.lastSaved = this.webBrowser1.DocumentText;
}
}
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
// Check if it changed
if (this.lastSaved != this.webBrowser1.DocumentText)
{
// TODO: ask user if he wants to save
// You can set e.Cancel = true to cancel loading the next page
}
}
QueryInterface()
IMarkupContainer2
的文檔,然后使用您自己的IHTMLChangeSink
實現調用IMarkupContainer2::RegisterForDirtyRange
。 當進行更改時,將調用您的IHTMLChangeSink::Notify
實現。
注意:在設置設計模式后執行此操作。 如果切換設計模式,文檔會重新加載並且事件掛鈎會丟失。
另一個解決方案,如果你實現IDocHostUIHandler
,你可以使用它的方法UpdateUI
這似乎有效 - IPersistFile接口的QueryInterface()
並使用IPersistFile::IsDirty方法和返回值S_OK
(如果臟或設計模式文檔已被修改)。
您不需要使用IPersistFile::Load
將內容加載到 Web 瀏覽器中, WebBrowser->Navigate()
也可以正常工作。
注意 - 在IPersistStream和IPersistStreamInit接口中也有相同的IsDirty()
方法
我不使用 C#,但重寫它應該相對容易。
bool IsEditorDirty(WebBrowser* WB)
{
// beware, if it fails to get Document and IPersistFile it will not register as dirty
bool isdirty = false;
IHTMLDocument2* pDoc2 = WB->Document;
if (pDoc2) {
IPersistFile* pPFile;
if (pDoc2->QueryInterface(IID_IPersistFile, (void**)&diPFile) == S_OK) {
isdirty = (pPFile->IsDirty() == S_OK);
pPFile->Release();
}
pDoc2->Release();
}
return isdirty;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.